/
cloneLLwithRandomPtr.js
75 lines (63 loc) · 1.68 KB
/
cloneLLwithRandomPtr.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { addEmitHelper } from 'typescript';
/**
leetcode 138: Copy List with Random Pointer
https://leetcode.com/problems/copy-list-with-random-pointer/
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
* // Definition for a Node.
* function Node(val,next,random) {
* this.val = val;
* this.next = next;
* this.random = random;
* };
*/
/**
* @param {Node} head
* @return {Node}
*/
function copyRandomList(head) {
const map = new Map();
return traverse(head);
function traverse(node) {
if (!node) return null;
if (!map.has(node)) {
const newNode = new Node(node.val);
map.set(node, newNode);
newNode.next = traverse(node.next);
newNode.random = traverse(node.random);
}
return map.get(node);
}
}
// iterative:
// const copyRandomList = function(head) {
// if (!head) return null;
// const dummy = new Node();
// const map = new Map();
// let src = head;
// let dest = dummy;
// while (src) {
// dest.next = new Node(src.val);
// map.set(src, dest.next);
// src = src.next;
// dest = dest.next;
// }
// for (let [src, dest] of map) {
// dest.random = map.get(src.random) || null;
// }
// return dummy.next;
// };
function c(node) {
const map = new Map();
return helper(node);
function helper(node) {
if (!node) return;
if (!map.has(node)) {
const newNode = new Node(node.val);
map.set(node, newNode);
newNode.next = helper(node.next);
newNode.random = helper(node.random);
}
return map.get(node);
}
}