-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path138. Copy List with Random Pointer.java
72 lines (57 loc) · 1.46 KB
/
138. 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
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
copyList(head);
copyRandomPointers(head);
return extractDeepCopy(head);
}
public void copyList(Node head){
Node curr = head;
while(curr != null)
{
Node forw = curr.next;
Node node = new Node(curr.val);
curr.next = node;
node.next = forw;
curr = forw;
}
}
public void copyRandomPointers(Node head){
Node curr = head;
while(curr != null)
{
Node ran = curr.random;
if(ran != null)
{
curr.next.random = ran.next;
}
curr = curr.next.next;
}
}
public Node extractDeepCopy(Node head)
{
Node dummy = new Node(-1);
Node prev = dummy;
Node curr = head;
while(curr != null)
{
prev.next = curr.next;
curr.next = curr.next.next;
prev = prev.next;
curr = curr.next;
}
return dummy.next;
}
}