-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCloneLL.java
54 lines (43 loc) · 1.4 KB
/
CloneLL.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
class Node {
int data;
Node next, random;
Node(int d)
{
data = d;
next = random = null;
}
}
public class CloneLL{
// Function to clone a linked list with next and random pointer.
Node copyList(Node head) {
if (head == null) return null;
// Step 1: Copy each node and insert the copied node after the original node.
Node curr = head;
while (curr != null) {
Node copy = new Node(curr.data);
copy.next = curr.next;
curr.next = copy;
curr = copy.next;
}
// Step 2: Assign random pointers to the copied nodes.
curr = head;
while (curr != null) {
if (curr.random != null) {
curr.next.random = curr.random.next;
}
curr = curr.next.next;
}
// Step 3: Separate the cloned list from the original list.
curr = head;
Node dummy = new Node(0); // Dummy node to help in separating the list.
Node copyCurr = dummy;
while (curr != null) {
copyCurr.next = curr.next;
curr.next = curr.next.next; // Restore the original list.
curr = curr.next; // Move to the next original node.
copyCurr = copyCurr.next; // Move to the next cloned node.
}
// Return the head of the copied list.
return dummy.next;
}
}