-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathCopyRandomListPointer
79 lines (65 loc) · 2 KB
/
CopyRandomListPointer
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
/**
* 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 {
public RandomListNode copyRandomList(RandomListNode head) {
RandomListNode X =head;
RandomListNode Y;
HashMap<RandomListNode ,RandomListNode> HT = new HashMap<>();
while(X != null){
Y = new RandomListNode(X.label);
Y.next = null;
Y.random = null;
HT.put(X,Y);
X=X.next;
}
X = head;
while(X !=null){
Y = HT.get(X);
Y.next = HT.get(X.next);
Y.random = HT.get(X.random);
X=X.next;
}
return HT.get(head);
}
}
//O(n) Approrach
/**
* 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 {
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) return null;
//copy same node at alternate position
for (RandomListNode iter = head; iter != null; iter = iter.next.next) {
RandomListNode copy = new RandomListNode(iter.label);
copy.next = iter.next;
iter.next = copy;
}
//copy Random Pointers
for (RandomListNode iter = head; iter != null; iter = iter.next.next){
if (iter.random != null)
iter.next.random = iter.random.next;
}
//Seprate Pointers for ODD and EVEN , Even List Contains the random pointers clone
RandomListNode evenHead = head.next, odd = head, even = evenHead;
while (even.next != null) {
odd.next = odd.next.next;
even.next = even.next.next;
odd = odd.next;
even = even.next;
}
odd.next = null;
return evenHead;
}
}