-
-
Notifications
You must be signed in to change notification settings - Fork 609
/
Copy pathCopyListwithRandomPointer.java
89 lines (70 loc) · 2.35 KB
/
CopyListwithRandomPointer.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
package problems.hard;
import problems.utils.RandomListNode;
import java.util.HashMap;
import java.util.Map;
/**
* Created by sherxon on 1/6/17.
*/
public class CopyListwithRandomPointer {
/**
* This duplicates each node next to original one. on the second round of iteration it sets random elements
* on the third round of iteration we remove original ones and duplicates are left. 3 iteration and no extra space
*/
public RandomListNode copyRandomList2(RandomListNode head) {
if (head == null) return null;
//duplicate each node
RandomListNode x = head;
while (x != null) {
RandomListNode copy = new RandomListNode(x.label);
copy.next = x.next;
x.next = copy;
x = copy.next;
}
//set random to duplicated nodes
x = head;
while (x != null) {
RandomListNode copy = x.next;
if (x.random != null)
copy.random = x.random.next;
x = copy.next;
}
//remove original nodes
RandomListNode fakeHead = new RandomListNode(0);
RandomListNode Head = fakeHead;
x = head;
while (x != null) {
RandomListNode next = x.next.next;
RandomListNode copy = x.next;
fakeHead.next = copy;
fakeHead = fakeHead.next;
x.next = next;
x = next;
}
return Head.next;
}
/**
* Two round iteration solution using hashmap to find copy pair of original node.
*/
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) return null;
Map<RandomListNode, RandomListNode> map = new HashMap<>();
RandomListNode x = head;
RandomListNode newhead = new RandomListNode(0);
RandomListNode newheadHelper = newhead;
while (x != null) {
newheadHelper.next = new RandomListNode(x.label);
map.put(x, newheadHelper.next);
x = x.next;
newheadHelper = newheadHelper.next;
}
newheadHelper = newhead.next;
x = head;
while (x != null) {
if (x.random != null)
newheadHelper.random = map.get(x.random);
newheadHelper = newheadHelper.next;
x = x.next;
}
return newhead.next;
}
}