Skip to content

Create Copy_List_with_Random _Pointer.java #391

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
44 changes: 44 additions & 0 deletions Java/Copy_List_with_Random _Pointer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
class Solution {
public Node copyRandomList(Node head) {

//creating a new (deep copy node) and connecting 1st original node to deep copy node
// then deep copy node to 2nd original node so on...

Node iter=head;
Node front=head;

while(iter!=null){
front=iter.next;
Node copy=new Node(iter.val);
iter.next=copy;
copy.next=front;
iter=front;
}

//connecting ramdom links

iter=head;
while(iter!=null){
if(iter.random!=null)
iter.next.random=iter.random.next; //imp
iter=iter.next.next; // iter moves to next original node
}

//segrigation of two lists
iter=head;
Node pseudo=new Node(0); //new node used for track of head to return the deep copy list
Node copy=pseudo;

while(iter!=null){
front=iter.next.next;//iter moves to next original node
copy.next=iter.next; //deep copy links to next deep copy
iter.next=front; // original node links to next original node
copy=copy.next; //copy pointer moves to next copy node
iter=iter.next; //iter pointer moves to next original node
}

return pseudo.next;


}
}