-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathCloneAlinkedList.java
46 lines (34 loc) · 1.02 KB
/
CloneAlinkedList.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
class Clone {
// data
// next
// arb
Node copyList(Node head) {
// Step 1
Node temp = head, nextNode = head;
while(temp != null) {
nextNode = temp.next;
Node toAdd = new Node(temp.data);
temp.next = toAdd;
toAdd.next = nextNode;
temp = nextNode;
}
// Step 2 Random Pointers
temp = head;
while(temp != null) {
if(temp.arb != null) temp.next.arb = temp.arb.next;
temp = temp.next.next;
}
// Step 3 Remove Connection
temp = head;
Node dummy = new Node(-1), ptr = dummy;
Node fast = head, slow = head;
while(slow != null) {
fast = slow.next.next;
ptr.next = slow.next;
ptr = ptr.next;
slow.next = fast;
slow = fast;
}
return dummy.next;
}
}