Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

复制带随机指针的链表 #112

Open
louzhedong opened this issue Dec 21, 2018 · 0 comments
Open

复制带随机指针的链表 #112

louzhedong opened this issue Dec 21, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处 LeetCode 算法第138题

给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。

要求返回这个链表的深度拷贝。

思路

用一个map来保存已访问过的节点

解答

/**
 * @param {RandomListNode} head
 * @return {RandomListNode}
 */
function copyRandomList(head) {
  return copy(head, {});
}

function copy(node, map) {
  if (!node) return node;
  if (map[node.label]) return map[node.label];

  let n = new RandomListNode(node.label);

  map[node.label] = n;

  n.next = copy(node.next, map);
  n.random = copy(node.random, map);

  return n;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant