Skip to content

Commit a3477bd

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 a3477bd

File tree

1 file changed

+51
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)