剑指 Offer 35. 复杂链表的复制

47 阅读1分钟

剑指 Offer 35. 复杂链表的复制

image.png

思路:第一次遍历链表是为了克隆原始链表中的每一个节点

第二次遍历链表是 为了解决克隆后的链表 各个节点的next和random指向问题

/**
 * // Definition for a Node.
 * function Node(val, next, random) {
 *    this.val = val;
 *    this.next = next;
 *    this.random = random;
 * };
 */
function Node(val, next, random) {
   this.val = val;
   this.next = next;
   this.random = random;
};

const copyRandomList = head => {
    if (!head) return null;
    const m = new Map();
    let node = head;
    // 遍历节点 然后克隆每一个节点,放入Map中,其中的key是node value为克隆后的node
    while (node) {
        m.set(node, new Node(node.val));
        node = node.next;
    }
    node = head;// 重置 为了下一次遍历
    // 二次遍历  为了解决克隆后的节点 next和random的指向
    while (node) {
        m.get(node).next = node.next ? m.get(node.next) : null;
        m.get(node).random = node.random ? m.get(node.random) : null;
        node = node.next;
    }
    // 返回第一个node对应的克隆node 就是满足要求的
    return m.get(head);
};


image.png