Clone a linked list with next and random pointer in O(1) space

Given a linked list having two pointers in each node. The first one points to the next node of the list, however, the other pointer is random and can point to any node of the list. Write a program that clones the given list in O(1) space, i.e., without any extra space.Â
Examples:Â
Input : Head of the below-linked list
Output : A new linked list identical to the original list.
In the previous posts Set-1 and Set-2 various methods are discussed, and O(n) space complexity implementation is also available.
In this post, we’ll be implementing an algorithm that’d require no additional space as discussed in Set-1.
Below is the Algorithm:Â
- Create the copy of node 1 and insert it between node 1 & node 2 in the original Linked List, create a copy of 2 and insert it between 2 & 3. Continue in this fashion, add the copy of N after the Nth nodeÂ
- Now copy the random link in this fashionÂ
original->next->random= original->random->next; /*TRAVERSE TWO NODES*/
- This works because original->next is nothing but a copy of the original and Original->random->next is nothing but a copy of the random.Â
 - Now restore the original and copy linked lists in this fashion in a single loop.Â
original->next = original->next->next;
copy->next = copy->next->next;
- Ensure that original->next is NULL and return the cloned list
Below is the implementation.Â
C++
// C++ program to clone a linked list with next// and arbit pointers in O(n) time#include <bits/stdc++.h>using namespace std;Â
// Structure of linked list Nodestruct Node{Â Â Â Â int data;Â Â Â Â Node *next,*random;Â Â Â Â Node(int x)Â Â Â Â {Â Â Â Â Â Â Â Â data = x;Â Â Â Â Â Â Â Â next = random = NULL;Â Â Â Â }};Â
// Utility function to print the list.void print(Node *start){    Node *ptr = start;    while (ptr)    {        cout << "Data = " << ptr->data << ", Random = "             << ptr->random->data << endl;        ptr = ptr->next;    }}Â
// This function clones a given linked list// in O(1) spaceNode* clone(Node *start){Â Â Â Â Node* curr = start, *temp;Â
    // insert additional node after    // every node of original list    while (curr)    {        temp = curr->next;Â
        // Inserting node        curr->next = new Node(curr->data);        curr->next->next = temp;        curr = temp;    }Â
    curr = start;Â
    // adjust the random pointers of the    // newly added nodes    while (curr)    {        if(curr->next)            curr->next->random = curr->random ?                                  curr->random->next : curr->random;Â
        // move to the next newly added node by        // skipping an original node        curr = curr->next?curr->next->next:curr->next;    }Â
    Node* original = start, *copy = start->next;Â
    // save the start of copied linked list    temp = copy;Â
    // now separate the original list and copied list    while (original && copy)    {        original->next =         original->next? original->next->next : original->next;Â
        copy->next = copy->next?copy->next->next:copy->next;        original = original->next;        copy = copy->next;    }Â
    return temp;}Â
// Driver codeint main(){Â Â Â Â Node* start = new Node(1);Â Â Â Â start->next = new Node(2);Â Â Â Â start->next->next = new Node(3);Â Â Â Â start->next->next->next = new Node(4);Â Â Â Â start->next->next->next->next = new Node(5);Â
    // 1's random points to 3    start->random = start->next->next;Â
    // 2's random points to 1    start->next->random = start;Â
    // 3's and 4's random points to 5    start->next->next->random =                    start->next->next->next->next;    start->next->next->next->random =                    start->next->next->next->next;Â
    // 5's random points to 2    start->next->next->next->next->random =                                      start->next;Â
    cout << "Original list : \n";    print(start);Â
    cout << "\nCloned list : \n";    Node *cloned_list = clone(start);    print(cloned_list);Â
    return 0;} |
Java
// Java program to clone a linked list with next// and arbit pointers in O(n) timeimport java.util.*;import java.io.*;Â
public class GfG {Â
    // Structure of linked list Node    static class Node {        int data;        Node next, random;        Node(int x)        {            data = x;            next = random = null;        }    }Â
    // Utility function to print the list.    static void print(Node start)    {        Node ptr = start;        while (ptr != null) {            System.out.println("Data = " + ptr.data                               + ", Random = "                               + ptr.random.data);            ptr = ptr.next;        }    }Â
    // This function clones a given    // linked list in O(1) space    static Node clone(Node start)    {        Node curr = start, temp = null;Â
        // insert additional node after        // every node of original list        while (curr != null) {            temp = curr.next;Â
            // Inserting node            curr.next = new Node(curr.data);            curr.next.next = temp;            curr = temp;        }        curr = start;Â
        // adjust the random pointers of the        // newly added nodes        while (curr != null) {            if (curr.next != null)                curr.next.random = (curr.random != null)                                       ? curr.random.next                                       : curr.random;Â
            // move to the next newly added node by            // skipping an original node            curr = curr.next.next;                           }Â
        Node original = start, copy = start.next;Â
        // save the start of copied linked list        temp = copy;Â
        // now separate the original list and copied list        while (original != null) {            original.next =original.next.next;Â
          copy.next = (copy.next != null) ? copy.next.next                                            : copy.next;            original = original.next;            copy = copy.next;        }        return temp;    }Â
    // Driver code    public static void main(String[] args)    {        Node start = new Node(1);        start.next = new Node(2);        start.next.next = new Node(3);        start.next.next.next = new Node(4);        start.next.next.next.next = new Node(5);Â
        // 1's random points to 3        start.random = start.next.next;Â
        // 2's random points to 1        start.next.random = start;Â
        // 3's and 4's random points to 5        start.next.next.random = start.next.next.next.next;        start.next.next.next.random            = start.next.next.next.next;Â
        // 5's random points to 2        start.next.next.next.next.random = start.next;Â
        System.out.println("Original list : ");        print(start);Â
        System.out.println("Cloned list : ");        Node cloned_list = clone(start);        print(cloned_list);    }}Â
// This code is contributed by Prerna Saini. |
C#
// C# program to clone a linked list with // next and arbit pointers in O(n) time using System;Â
class GFG { Â
// Structure of linked list Node class Node { Â Â Â Â public int data; Â Â Â Â public Node next, random; Â Â Â Â public Node(int x) Â Â Â Â { Â Â Â Â Â Â Â Â data = x; Â Â Â Â Â Â Â Â next = random = null; Â Â Â Â } } Â
// Utility function to print the list. static void print(Node start) { Â Â Â Â Node ptr = start; Â Â Â Â while (ptr != null) Â Â Â Â { Â Â Â Â Â Â Â Â Console.WriteLine("Data = " + ptr.data + Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ", Random = " +Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ptr.random.data); Â Â Â Â Â Â Â Â ptr = ptr.next; Â Â Â Â } } Â
// This function clones a given // linked list in O(1) space static Node clone(Node start) { Â Â Â Â Node curr = start, temp = null; Â
    // insert additional node after     // every node of original list     while (curr != null)     {         temp = curr.next; Â
        // Inserting node         curr.next = new Node(curr.data);         curr.next.next = temp;         curr = temp;     }     curr = start; Â
    // adjust the random pointers of     // the newly added nodes     while (curr != null)     {         if(curr.next != null)             curr.next.random = (curr.random != null)                     ? curr.random.next : curr.random; Â
        // move to the next newly added node         // by skipping an original node         curr = (curr.next != null) ? curr.next.next                                         : curr.next;     } Â
    Node original = start, copy = start.next; Â
    // save the start of copied linked list     temp = copy; Â
    // now separate the original list     // and copied list     while (original != null && copy != null)     {         original.next = (original.next != null)?                     original.next.next : original.next; Â
        copy.next = (copy.next != null) ? copy.next.next                                              : copy.next;         original = original.next;         copy = copy.next;     }     return temp; } Â
// Driver code public static void Main(String[] args) { Â Â Â Â Node start = new Node(1); Â Â Â Â start.next = new Node(2); Â Â Â Â start.next.next = new Node(3); Â Â Â Â start.next.next.next = new Node(4); Â Â Â Â start.next.next.next.next = new Node(5); Â
    // 1's random points to 3     start.random = start.next.next; Â
    // 2's random points to 1     start.next.random = start; Â
    // 3's and 4's random points to 5     start.next.next.random = start.next.next.next.next;     start.next.next.next.random = start.next.next.next.next; Â
    // 5's random points to 2     start.next.next.next.next.random = start.next; Â
    Console.WriteLine("Original list : ");     print(start); Â
    Console.WriteLine("Cloned list : ");     Node cloned_list = clone(start);     print(cloned_list); } } Â
// This code has been contributed // by Rajput-Ji |
Python
'''Python program to clone a linked list with next and arbitrary pointers''''''Done in O(n) time with O(1) extra space'''Â
class Node:Â Â Â Â '''Structure of linked list node'''Â
    def __init__(self, data):        self.data = data        self.next = None        self.random = NoneÂ
def clone(original_root):Â Â Â Â '''Clone a doubly linked list with random pointer'''Â Â Â Â '''with O(1) extra space'''Â
    '''Insert additional node after every node of original list'''    curr = original_root    while curr != None:        new = Node(curr.data)        new.next = curr.next        curr.next = new        curr = curr.next.nextÂ
    '''Adjust the random pointers of the newly added nodes'''    curr = original_root    while curr != None:        curr.next.random = curr.random.next        curr = curr.next.nextÂ
    '''Detach original and duplicate list from each other'''    curr = original_root    dup_root = original_root.next    while curr.next != None:        tmp = curr.next        curr.next = curr.next.next        curr = tmpÂ
    return dup_rootÂ
def print_dlist(root):Â Â Â Â '''Function to print the doubly linked list'''Â
    curr = root    while curr != None:        print('Data =', curr.data, ', Random =', curr.random.data)        curr = curr.nextÂ
####### Driver code #######'''Create a doubly linked list'''original_list = Node(1)original_list.next = Node(2)original_list.next.next = Node(3)original_list.next.next.next = Node(4)original_list.next.next.next.next = Node(5)Â
'''Set the random pointers'''Â
# 1's random points to 3original_list.random = original_list.next.nextÂ
# 2's random points to 1original_list.next.random = original_listÂ
# 3's random points to 5original_list.next.next.random = original_list.next.next.next.nextÂ
# 4's random points to 5original_list.next.next.next.random = original_list.next.next.next.nextÂ
# 5's random points to 2original_list.next.next.next.next.random = original_list.nextÂ
'''Print the original linked list'''print('Original list:')print_dlist(original_list)Â
'''Create a duplicate linked list'''cloned_list = clone(original_list)Â
'''Print the duplicate linked list'''print('\nCloned list:')print_dlist(cloned_list)Â
'''This code is contributed by Shashank Singh''' |
Javascript
<script>Â
// Javascript program to clone a linked list with next // and arbit pointers in O(n) time Â
Â
    // Structure of linked list Node     class Node {Â
constructor(x) {Â Â Â Â Â Â Â Â Â Â Â Â this.data = x;Â Â Â Â Â Â Â Â Â Â Â Â this.next = this.random = null;Â Â Â Â Â Â Â Â }Â Â Â Â }Â
    // Utility function to print the list.    function print(start) {var ptr = start;        while (ptr != null) {            document.write(            "Data = " +             ptr.data + ", Random = "            + ptr.random.data+"<br/>"            );            ptr = ptr.next;        }    }Â
    // This function clones a given    // linked list in O(1) space    function clone(start) {var curr = start, temp = null;Â
        // insert additional node after        // every node of original list        while (curr != null) {            temp = curr.next;Â
            // Inserting node            curr.next = new Node(curr.data);            curr.next.next = temp;            curr = temp;        }        curr = start;Â
        // adjust the random pointers of the        // newly added nodes        while (curr != null) {            if (curr.next != null)                curr.next.random = (curr.random != null) ?                 curr.random.next : curr.random;Â
            // move to the next newly added node by            // skipping an original node            curr = (curr.next != null) ?             curr.next.next : curr.next;        }Â
var original = start, copy = start.next;Â
        // save the start of copied linked list        temp = copy;Â
        // now separate the original list and copied list        while (original != null && copy != null) {            original.next = (original.next != null) ?             original.next.next : original.next;Â
            copy.next = (copy.next != null) ?            copy.next.next : copy.next;            original = original.next;            copy = copy.next;        }        return temp;    }Â
    // Driver code     var start = new Node(1);        start.next = new Node(2);        start.next.next = new Node(3);        start.next.next.next = new Node(4);        start.next.next.next.next = new Node(5);Â
        // 1's random points to 3        start.random = start.next.next;Â
        // 2's random points to 1        start.next.random = start;Â
        // 3's and 4's random points to 5        start.next.next.random =         start.next.next.next.next;        start.next.next.next.random =         start.next.next.next.next;Â
        // 5's random points to 2        start.next.next.next.next.random =         start.next;Â
        document.write("Original list : <br/>");        print(start);        document.write("<br>");        document.write("Cloned list : <br/>");        var cloned_list = clone(start);        print(cloned_list);Â
Â
// This code contributed by aashish1995Â
</script> |
Original list : Data = 1, Random = 3 Data = 2, Random = 1 Data = 3, Random = 5 Data = 4, Random = 5 Data = 5, Random = 2 Cloned list : Data = 1, Random = 3 Data = 2, Random = 1 Data = 3, Random = 5 Data = 4, Random = 5 Data = 5, Random = 2
Time Complexity: O(n) As we are moving through the list thrice, i.e. 3n , Â but in asymptotic notations we drop the constant terms
Auxiliary Space: O(1) As no extra space is used. The n nodes which are inserted in between the nodes was already required to clone the list, so we can say that we did not use any extra space.
This article is contributed by Ashutosh Kumar 😀 If you like zambiatek and would like to contribute, you can also write an article using write.zambiatek.com or mail your article to review-team@zambiatek.com. See your article appearing on the zambiatek main page and help other Geeks.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!




