Skip to content

Commit 0aa84ae

Browse files
authored
Create Copy_List_With_Random_Pointer.java
The Copy List with Random Pointer problem involves creating a deep copy of a linked list where each node has a next pointer and a random pointer (pointing to any other node or null). The solution uses a three-step approach: first, clone each node and place the clone next to the original; second, set the random pointers of each clone based on the original nodes' random pointers; finally, separate the original and cloned lists. This method efficiently creates the copied list with O(n) time complexity and O(1) auxiliary space.
1 parent 202879a commit 0aa84ae

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.thealgorithms.datastructures.lists;
2+
3+
class Node {
4+
int val;
5+
Node next;
6+
Node random;
7+
8+
public Node(int val) {
9+
this.val = val;
10+
this.next = null;
11+
this.random = null;
12+
}
13+
}
14+
15+
public class Solution {
16+
public Node copyRandomList(Node head) {
17+
if (head == null) {
18+
return null;
19+
}
20+
21+
// Step 1: Clone each node and insert it next to the original node
22+
Node current = head;
23+
while (current != null) {
24+
Node clone = new Node(current.val);
25+
clone.next = current.next;
26+
current.next = clone;
27+
current = clone.next;
28+
}
29+
30+
// Step 2: Set the random pointers for the cloned nodes
31+
current = head;
32+
while (current != null) {
33+
if (current.random != null) {
34+
current.next.random = current.random.next;
35+
}
36+
current = current.next.next;
37+
}
38+
39+
// Step 3: Separate the original and cloned lists
40+
Node original = head, copy = head.next;
41+
Node clonedHead = head.next;
42+
while (original != null) {
43+
original.next = original.next.next;
44+
if (copy.next != null) {
45+
copy.next = copy.next.next;
46+
}
47+
original = original.next;
48+
copy = copy.next;
49+
}
50+
51+
return clonedHead;
52+
}
53+
}
54+

0 commit comments

Comments
 (0)