-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCopyListRandomPointer.java
69 lines (49 loc) · 1.61 KB
/
CopyListRandomPointer.java
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
package techQuestions;
import java.util.HashMap;
public class CopyListRandomPointer {
public static void main(String[] args) {
// TODO Auto-generated method stub
// [[7,null],[13,0],[11,4],[10,2],[1,0]]
Node node = new Node(7);
node.random = null;
// System.out.println(node.val);
node.next = new Node(13);
node.next.random = node;
// System.out.println(node.next.random.val);
// second node's existence
node.next.next = new Node(11);
node.next.next.next = new Node(10);
node.next.next.next.random = node.next.next;
// System.out.println(node.next.next.next.random.val);
node.next.next.next.next = new Node(1);
node.next.next.next.next.random = node;
// System.out.println(node.next.next.next.next.random.val);
// second node's random pointer
node.next.next.random = node.next.next.next.next;
// System.out.println(node.next.next.random.val);
Node output = copyRandomList(node);
// System.out.println("-----------");
while (output != null) {
System.out.println(output.val);
output = output.next;
}
}
static HashMap<Node, Node> visitedHash = new HashMap<>();
public static Node copyRandomList(Node head) {
// implement recursively and with a hash map!
// first, a recursive program must always have a base case!
if (head == null) {
return null;
}
if (visitedHash.containsKey(head)) {
return visitedHash.get(head);
}
Node node = new Node(head.val);
node.next = null;
node.random = null;
visitedHash.put(head, node);
node.next = copyRandomList(head.next);
node.random = copyRandomList(head.random);
return node;
}
}