Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Copy_List_With_Random_Pointer.java #6003

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.thealgorithms.datastructures.lists;

class Node {
int val;
Node next;
Node random;

public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}

public class Solution {
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}

// Step 1: Clone each node and insert it next to the original node
Node current = head;
while (current != null) {
Node clone = new Node(current.val);
clone.next = current.next;
current.next = clone;
current = clone.next;
}

// Step 2: Set the random pointers for the cloned nodes
current = head;
while (current != null) {
if (current.random != null) {
current.next.random = current.random.next;
}
current = current.next.next;
}

// Step 3: Separate the original and cloned lists
Node original = head, copy = head.next;
Node clonedHead = head.next;
while (original != null) {
original.next = original.next.next;
if (copy.next != null) {
copy.next = copy.next.next;
}
original = original.next;
copy = copy.next;
}

return clonedHead;
}
}

Loading