Clone a linked list with next and random pointer | Practice | GeeksforGeeks

You are given a special linked list with N nodes where each node has a next pointer pointing to its next node. You are also given M random pointers, where you will be given M number of pairs denoting two nodes a and b  i.e. a->arb = b.
Construct a copy of the given list. The copy should consist of exactly N new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.
For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y.
Return the head of the copied linked list.
Example 1:
Input:
N = 4, M = 2
value = {1,2,3,4}
pairs = {{1,2},{2,4}}
Output: 1
Explanation: In this test case, there
are 4 nodes in linked list.  Among these
4 nodes,  2 nodes have arbitrary pointer
set, rest two nodes have arbitrary pointer
as NULL. Second line tells us the value
of four nodes. The third line gives the
information about arbitrary pointers.
The first node arbitrary pointer is set to
node 2.  The second node arbitrary pointer
is set to node 4.

Example 2:
Input:
N = 4, M = 2
value[] = {1,3,5,9}
pairs[] = {{1,1},{3,4}}
Output: 1
Explanation: In the given testcase ,
applying the method as stated in the
above example, the output will be 1.


Your Task:
The task is to complete the function copyList() which takes one argument the head of the linked list to be cloned and should return the head of the cloned linked list.
NOTE : 
1. If there is any node whose arbitrary pointer is not given then it's by default NULL. 
2. Your solution return an output 1 if your clone linked list is correct, else it returns 0.
Expected Time Complexity : O(n)
Expected Auxilliary Space : O(1)
Constraints:
1 <= N <= 100
1 <= M <= N
1 <= a, b <= 100
0
fauzansiddiqui13 hours ago
Node *copyList(Node *head)   {       Node* originalNode = head;       Node* cloneHead = NULL;       Node* cloneTail = NULL;       // Step 1: Simple Cloning       while(originalNode != NULL){           insertAtTail(cloneHead,cloneTail,originalNode->data);           originalNode = originalNode->next;       }       originalNode = head;       Node* dupNode = cloneHead;       // Step 2 : Chaining both LL together       while(originalNode != NULL && dupNode != NULL){           Node* next = originalNode->next;           originalNode->next = dupNode;           originalNode = next;                      next = dupNode->next;           dupNode->next = originalNode;           dupNode = next;       }              // Step 3: Linking Random pointers       originalNode = head;       while(originalNode != NULL){           if(originalNode->next != NULL)          originalNode->next->arb = originalNode->arb ? originalNode->arb->next : originalNode->arb;                  originalNode = originalNode->next->next;       }       // Step 4: Revert Changes       originalNode = head;       dupNode = cloneHead;       while(originalNode != NULL && dupNode != NULL){           originalNode->next = dupNode->next;           originalNode = originalNode->next;           if(originalNode != NULL)           dupNode->next = originalNode->next;           dupNode = dupNode->next;       }              // Step 5: Return Ans       return cloneHead;              //Write your code here   }
0
chiraga581
This comment was deleted.
0
harisrashid41212034 days ago
 void arrangeChains(Node *head,Node *cloneHead){              Node *current = head;       Node *forward = cloneHead;              while(current != NULL && forward != NULL){           if(current->arb != NULL)                    forward->arb = current->arb->next;           else               forward->arb = current->arb;                                 current->next = forward->next;           current = current->next;                      if(current != NULL)               forward->next = current->next;           forward = forward->next;                             } // why few test cases are failing
0
tthakare731 week ago
//java solution 
class Clone {
    //Function to clone a linked list with next and random pointer.
    Node copyList(Node head) {
        //create linking in origin an copy
        Node dummy = head;
        while(dummy != null){
            Node temp = dummy.next;
            dummy.next = new Node(dummy.data);
            dummy.next.next = temp;
            dummy = temp;
        }
        
        //set random pointer
        dummy = head;
        while(dummy != null){
            if(dummy.next != null){
                dummy.next.arb = dummy.arb != null ? dummy.arb.next : null;
            }
            dummy = dummy.next.next;
        }
        
        //seprate original and copy
        dummy = head;
        Node result = head.next, copy = head.next;
        while(dummy != null){
            dummy.next = dummy.next.next;
            result.next = result.next != null ? result.next.next : null;
            dummy = dummy.next;
            result = result.next;
        }

        return copy;
    }
}
0
khushbugarg791 week ago
 private:
    void insertAtTail(Node *head,Node *tail,int data){
        Node* newdata = new Node(data);
        if(head==NULL){
            head=newdata;
            tail=newdata;
            return;
        }
        else{
            tail->next=newdata;
            tail=newdata;
        }
       
    }
    public:
    Node *copyList(Node *head)
    {
        //clone the list
        Node* originalHead=head;
        Node* cloneHead=NULL;
        Node* cloneTail=NULL;
        while(originalHead!=NULL){
            insertAtTail(cloneHead,cloneTail,originalHead->data);
            originalHead=originalHead->next;
        }
        
        //create map
        
        unordered_map<Node* , Node*> myMap;
        originalHead=head;
        Node* temp = cloneHead;
        while(originalHead!=NULL){
            myMap[originalHead]=temp;
            originalHead=originalHead->next;
            temp=temp->next;
        }
        
        //random the ptr
        originalHead=head;
        temp = cloneHead;
        while(originalHead!=NULL){
            temp->arb= myMap[originalHead->arb];
            originalHead=originalHead->next;
            temp=temp->next;
        }
        return cloneHead;
    }
please help. why is this not working. segmentation fault
0
ns2847192 weeks ago
Firstly i am modify the original linkedlist .We have to set the random  pointer We have to seperate the original linked list 
Firstly i am modify the original linkedlist .
We have to set the random  pointer 
We have to seperate the original linked list 
CODE : - 
  Node *copyList(Node *head)   {       //Write your code here       Node* curr = head;       while(curr!=NULL) {           Node* temp = curr->next;           curr->next = new Node(curr->data);           curr->next->next = temp;           curr = temp;       }              curr = head;              // Set arb(random) pointers       while(curr!= NULL) {           if(curr->next!= NULL) {               curr->next->arb = curr->arb != NULL ? curr->arb->next : NULL;           }                      curr = curr->next->next;       }              // Separate two linked list       Node* ori = head;       Node* copy = head->next;       Node* temp = copy;       while(ori!= NULL) {           ori->next = ori->next->next;           copy->next = (copy->next != NULL) ? copy->next->next  : copy->next;           ori = ori->next;           copy = copy->next;       }              return temp;    }
 
 
+1
madhajaswanth3 weeks ago
Node copyList(Node head) {              Map<Node,Node> map = new HashMap<Node,Node>();              Node ptr = head;                     // just store a new node corresponding to the current node       while(ptr != null){           map.put(ptr,new Node(ptr.data));           ptr = ptr.next;       }              ptr = head;              // this is the head of the result       Node myHead = null;                     while(ptr != null){                      // getting the next of current node           Node next = ptr.next;           // getting the random of current node           Node random = ptr.arb;                      // getting the next of my list           Node myNext = map.get(next);                      // getting the random of my list           Node myRandom = map.get(random);                      // getting the current node of my list           Node myCurr = map.get(ptr);                      // update the head           if(myHead == null){               myHead = curr;           }                      // update my list           myCurr.next = myNext;           myCurr.arb = myRandom;                      // move the pointer           ptr = ptr.next;                  }       return myHead;   }
+1
sangrambachu3 weeks ago
class Clone {
    //Function to clone a linked list with next and random pointer.
    Node copyList(Node head) {
        // your code here
        
        //Insert new node
        Node curr = head;
        while(curr != null) {
            Node temp = curr.next;
            curr.next = new Node(curr.data);
            curr.next.next = temp;
            curr = temp;
        }
        
        curr = head;
        
        // Set arb pointers
        while(curr != null) {
            if(curr.next != null) {
                curr.next.arb = curr.arb != null ? curr.arb.next : null;
            }
            
            curr = curr.next.next;
        }
        
        // Separate two linked list
        Node ori = head;
        Node copy = head.next;
        Node temp = copy;
        while(ori != null) {
            ori.next = ori.next.next;
            copy.next = (copy.next != null) ? copy.next.next  : copy.next;
            ori = ori.next;
            copy = copy.next;
        }
        
        return temp;
    }
}
+1
mandeepjain004 weeks ago
Method 1 :- O(n)TS O(n)AS
Create a newList by using next abhi dont use random
store the address of given node and newly created node in map like  given list k node ka address will be the key and new node ka address will be value (sab nodes ka liye)
now thing left is to place random  by using map
iterate both the list simultaneously
map me given list ka jo random hai vo (mean ye key ki value ) vo cloneList ka random hoga
 
if you understand what i share please practice First :) 
 
code..
 
 Node *copyList(Node *head)
    {
        Node *cloneHead = NULL, *cloneTail = NULL, *temp = head;
        unordered_map<Node*,Node*> um;
        //creating new list 
        while(temp){
                Node *newnode = new Node(temp->data);
                //mapping address
                um.insert({temp,newnode});
                if(cloneHead == NULL){
                    cloneHead = newnode;
                    cloneTail = newnode;
                }else{
                    cloneTail->next = newnode;
                    cloneTail = newnode;
                }
            temp=temp->next;
        }
        //just placing rigt random
        temp = head;
        Node *temp2 = cloneHead;
        while(temp && temp2){
            temp2->arb = um[temp->arb];
            temp = temp->next;
            temp2 = temp2->next;
        }
        
        return cloneHead;
    }
 
Method2
 
first we copy original List as it and we will skip random pointers
merge both list such way each next of original list  pointing to clone list node. and next of clone list pointing to next of original list node
now set-up random pointertravel original list and for eacj nodeorignal list ka next (means clone list ka node) == orignal list k random ka next
travel original list and for eacj node
orignal list ka next (means clone list ka node) =
= orignal list k random ka next
revert the changes done in step2 means jo next me changes kiya tha dono list me usko revert kroorignal ka next hojayga clone ka nextclone ka next hojayga orignal k next ka next
orignal ka next hojayga clone ka next
clone ka next hojayga orignal k next ka next
return head
Code
.....
 Node *copyList(Node *head)
    {
        //Method 2
        Node *temp = head, *cloneHead = NULL, *cloneTail = NULL, *upcoming = NULL;
        //creating copy of orignal lis
        while(temp){
            Node *newNode = new Node(temp->data);
            if(cloneHead == NULL){
                cloneHead = newNode;
                cloneTail = newNode;
            }else{
                cloneTail->next = newNode;
                cloneTail = newNode;
            }
            temp = temp->next;
        }
        //conecting orignal node with clone node(zig zag)
        Node *orignalNode = head, *cloneNode = cloneHead;
        while(orignalNode!=NULL && cloneNode!=NULL){
            upcoming = orignalNode->next;
            orignalNode->next = cloneNode;
            orignalNode = upcoming;
            
            upcoming = cloneNode->next;
            cloneNode->next = orignalNode;
            cloneNode = upcoming;
        }
        //setting up random
        temp = head;
        while(temp != NULL){
            if(temp->next != NULL){
               temp->next->arb = (temp->arb != NULL) ? temp->arb->next : NULL;
            }
            temp=temp->next->next;
        }
      
        
        //remove changes done in orignal list
        orignalNode = head;
        cloneNode = cloneHead;
        while(cloneNode && orignalNode){
            orignalNode->next = cloneNode->next;
            orignalNode = orignalNode->next;
            if(orignalNode != NULL) cloneNode->next = orignalNode->next;
            cloneNode = cloneNode->next;
        }
        return cloneHead;
    }
0
akshayaneja4 weeks ago
    copyList(head)
    {
        let original = head;
        let copy, copyHead;
        let o_c = new Map();
        
        while(original){
            if(!copy){
                copy = new Node(original.data);
                copyHead = copy;
            }else{
                copy.next = new Node(original.data);
                copy = copy.next;
            }
            o_c.set(original, copy);
            original = original.next;
        }
        

        while(head){
            if(head.arb){
                o_c.get(head).arb = o_c.get(head.arb);
            }
            head = head.next;
        }
        return copyHead;
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.