-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopy List with Random Pointer.java
More file actions
85 lines (71 loc) · 1.86 KB
/
Copy List with Random Pointer.java
File metadata and controls
85 lines (71 loc) · 1.86 KB
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
/*
// 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) {
if(head == null)return null;
//making a copy without random pointer;
Node dummy = new Node(-1);
Node pointer = dummy;
Node main = dummy;
Node ptr = head;
while(ptr != null){
Node node = new Node(ptr.val);
pointer.next = node;
pointer = pointer.next;
ptr = ptr.next;
}
pointer.next = null;
main = main.next;
dummy.next = null;
/////////////////////////////////////
Node ptr1 = head;
Node ptr2 = main;
Node curr = head;
while(curr != null){
ptr1 = ptr1.next;
curr.next = ptr2;
curr = curr.next;
ptr2 = ptr2.next;
curr.next = ptr1;
curr = curr.next;
}
/////////////////////////////////////
Node ptr3 = head;
while(ptr3 != null){
if(ptr3.random == null){
ptr3.next.random = null;
}
else{
ptr3.next.random = ptr3.random.next;
}
ptr3 = ptr3.next.next;
}
/////////////////////////////////////
Node start = head;
Node dup = head.next;
Node dupptr = head.next;
while(start != null){
start.next = dupptr.next;
start = start.next;
if(start == null){
dupptr.next = null;
}
else{
dupptr.next = start.next;
dupptr = dupptr.next;
}
}
return dup;
}
}