-
Notifications
You must be signed in to change notification settings - Fork 15
/
copy-list-with-random-pointer.java
103 lines (89 loc) · 2.94 KB
/
copy-list-with-random-pointer.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
/**
* @param head: The head of linked list with a random pointer.
* @return: A new head of a deep copy of the list.
*/
public RandomListNode copyRandomList(RandomListNode head) {
// write your code here
// Scan the list once, map all nodes into hashmap.
// scan second time to update pointer.
Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
RandomListNode runner = head;
while (runner != null) {
RandomListNode copy = new RandomListNode(runner.label);
map.put(runner, copy);
runner = runner.next;
}
runner = head;
while (runner != null) {
if (runner.next != null) {
map.get(runner).next = map.get(runner.next);
}
if (runner.random != null) {
map.get(runner).random = map.get(runner.random);
}
runner = runner.next;
}
return map.get(head);
}
}
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
/**
* @param head: The head of linked list with a random pointer.
* @return: A new head of a deep copy of the list.
*/
public RandomListNode copyRandomList(RandomListNode head) {
// write your code here
// insert copied node right after original node, time O(n)
// O(1) extra space.
RandomListNode runner = head;
// if (head == null) {
// return null;
// }
while (runner != null) {
RandomListNode next = runner.next;
RandomListNode copy = new RandomListNode(runner.label);
runner.next = copy;
copy.next = next;
runner = next;
}
runner = head;
while (runner != null) {
RandomListNode copy = runner.next;
RandomListNode next = copy.next;
if (runner.random != null) {
copy.random = runner.random.next;
}
runner = next;
}
RandomListNode copyHead = head.next;
RandomListNode copyRunner = copyHead;
runner = head;
// seperate two interleaved lists.
while ( runner != null) {
runner.next = copyRunner.next;
runner = runner.next;
if (runner != null) {
copyRunner.next = runner.next;
copyRunner = copyRunner.next;
}
}
return copyHead;
}
}