剑指Offer(复杂链表的复制)

372 阅读1分钟

复杂链表的复制

image.png

题目分析

  • 本题需要对含有random指针的链表进行复制,这里我们第一次迭代时先复制一份普通链表并且维护一个以源节点为键,新节点为值的map。在第二次迭代时对复制的链表添加random指针。

代码

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

/**
 * @param {Node} head
 * @return {Node}
 */
let copyRandomList = function (head) {
  if (!head) {
    return null;
  }
  let temp = head;
  const root = { next: null };
  let node = root;
  const map = new Map();
  while (temp) {
    node.val = temp.val;
    map.set(temp, node);
    if (temp.next) {
      node.next = { next: null };
      node = node.next;
    }
    temp = temp.next;
  }
  node = root;
  temp = head;
  while (temp) {
    if (temp.random) {
      node.random = map.get(temp.random);
    }
    node = node.next;
    temp = temp.next;
  }
  return root;
};