The Wayback Machine - https://web.archive.org/web/20240927155648/https://www.geeksforgeeks.org/a-linked-list-with-next-and-arbit-pointer/
Open In App

Clone a linked list with next and random pointer

Last Updated : 31 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a linked list of size N where each node has two links: next pointer pointing to the next node and random pointer to any random node in the list. The task is to create a clone of this linked list.

Example-of-linked-list-with-next-and-random-pointer

Example of Linked List with next and random pointer

[Naive Approach – 1] Using Hashing – O(2n) Time and O(2n) Space

The idea is to create a new node corresponding to each node in the original linked list and store the new nodes in a hash table. Now, again traverse the original linked list and update the next and random pointers of new nodes corresponding to every original node.

Illustration:


Steps to clone a linked list with next and random pointer:

  • Create a hash table, say mp to store the new nodes corresponding to their original nodes.
  • Traverse the original linked list and for every node, say curr,
    • Create a new node corresponding to curr and push them into a hash table, mp[curr] = new Node().
  • Again traverse the original linked list to update the next and random pointer of each new node, mp[curr]->next = mp[curr->next] and mp[curr]->random = mp[curr->random].
  • Return mp[head] as the head of the cloned linked list.

Below is the implementation of the above approach:

C++14
// C++ code to Clone a linked list with next and random
// pointer using Hashing 

#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    Node* next;
    Node* random;
  
    Node(int x) {
        data = x;
        next = random = NULL;
    }
};

// Function to clone the linked list
Node* cloneLinkedList(Node* head) {
  
    // Map to store new nodes corresponding to
      // their original nodes
    unordered_map<Node*, Node*> mp;
    Node *curr = head;
  
    // Traverse original linked list to store new 
      // nodes corresponding to original linked list
    while (curr != NULL) {
        mp[curr] = new Node(curr->data);
        curr = curr->next;
    }
    
      curr = head;
      
    // Loop to update the next and random pointers 
      // of new nodes 
    while (curr != NULL) {
        
          // Update the next pointer of new node
          mp[curr]->next = mp[curr->next];
      
          // Update the random pointer of new node
          mp[curr]->random = mp[curr->random];
      
          curr = curr->next;
    }
  
    // Return the head of the clone
    return mp[head];
}

// Function to print the linked list
void printList(Node* head) {
    while (head != NULL) {
        cout << head->data << "(";
          if(head->random)
              cout << head->random->data << ")";
          else 
              cout << "null" << ")";
        
          if(head->next != NULL)
              cout << " -> ";
        head = head->next;
    }
    cout << endl;
}

int main() {
  
    // Creating a linked list with random pointer
    Node* head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(3);
    head->next->next->next = new Node(4);
    head->next->next->next->next = new Node(5);
    head->random = head->next->next;
    head->next->random = head;
    head->next->next->random = head->next->next->next->next;
    head->next->next->next->random = head->next->next;
    head->next->next->next->next->random = head->next;
  
    // Print the original list
    cout << "Original linked list:\n";
    printList(head);
  
    // Function call
    Node* clonedList = cloneLinkedList(head);
  
    cout << "Cloned linked list:\n";
    printList(clonedList);
  
    return 0;
}
Java
// Java code to Clone a linked list with next and random
// pointer using Hashing

import java.util.HashMap;
import java.util.Map;

// Define the Node class
class Node {
    int data;
    Node next;
    Node random;
  
    Node(int x) {
        data = x;
        next = null;
        random = null;
    }
}

class GfG {

    // Function to clone the linked list
    static Node cloneLinkedList(Node head) {
  
        // Hash Map to store new nodes corresponding  
          // to their original nodes
        Map<Node, Node> mp = new HashMap<>();
        Node curr = head;
  
        // Traverse original linked list to store new nodes 
          // corresponding to original linked list
        while (curr != null) {
            mp.put(curr, new Node(curr.data));
            curr = curr.next;
        }
    
        curr = head;
    
        // Loop to update the next and random pointers
          // of new nodes 
        while (curr != null) {
        
            // Update the next pointer of new node
            Node newNode = mp.get(curr);
            newNode.next = mp.get(curr.next);
      
            // Update the random pointer of new node
            newNode.random = mp.get(curr.random);
      
            curr = curr.next;
        }
  
        // Return the head of the clone
        return mp.get(head);
    }

    // Function to print the linked list
    static void printList(Node head) {
        while (head != null) {
            System.out.print(head.data + "(");
            if (head.random != null)
                System.out.print(head.random.data + ")");
            else 
                System.out.print("null" + ")");
        
            if (head.next != null)
                System.out.print(" -> ");
            head = head.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
  
        // Creating a linked list with random pointer
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);
        head.random = head.next.next;
        head.next.random = head;
        head.next.next.random = head.next.next.next.next;
        head.next.next.next.random = head.next.next;
        head.next.next.next.next.random = head.next;
  
        // Print the original list
        System.out.println("Original linked list:");
        printList(head);
  
        // Function call
        Node clonedList = cloneLinkedList(head);
  
        System.out.println("Cloned linked list:");
        printList(clonedList);
    }
}
Python
# Python code to Clone a linked list with next and random
# pointer using Hashing

class Node:
    def __init__(self, x):
        self.data = x
        self.next = None
        self.random = None

# Function to clone the linked list
def clone_linked_list(head):
      
    # Dictionary to store new nodes corresponding 
    # to their original nodes
    mp = {}
    curr = head
    
    # Traverse original linked list to store new nodes 
    # corresponding to original linked list
    while curr is not None:
        mp[curr] = Node(curr.data)
        curr = curr.next
    
    curr = head
    
    # Loop to update the next and random pointers
    # of new nodes
    while curr is not None:
        new_node = mp[curr]
        
        # Update the next pointer of new node
        new_node.next = mp.get(curr.next)
        
        # Update the random pointer of new node
        new_node.random = mp.get(curr.random)
        curr = curr.next
    
    # Return the head of the clone
    return mp.get(head)

def print_list(head):
    curr = head
    while curr is not None:
        print(f'{curr.data}(', end='')
        if curr.random:
            print(f'{curr.random.data})', end='')
        else:
            print('null)', end='')
        
        if curr.next is not None:
            print(' -> ', end='')
        curr = curr.next
    print()

if __name__ == "__main__":
    
    # Creating a linked list with random pointer
    head = Node(1)
    head.next = Node(2)
    head.next.next = Node(3)
    head.next.next.next = Node(4)
    head.next.next.next.next = Node(5)
    
    head.random = head.next.next
    head.next.random = head
    head.next.next.random = head.next.next.next.next
    head.next.next.next.random = head.next.next
    head.next.next.next.next.random = head.next
    
    # Print the original list
    print("Original linked list:")
    print_list(head)
    
    # Function call
    cloned_list = clone_linked_list(head)
    
    print("Cloned linked list:")
    print_list(cloned_list)
C#
// C# code to Clone a linked list with next and random
// pointer using Hashing 

using System;
using System.Collections.Generic;

class Node {
    public int Data;
    public Node Next;
    public Node Random;

    public Node(int x) {
        Data = x;
        Next = null;
        Random = null;
    }
}

class GfG {
  
    // Function to clone the linked list
    public static Node CloneLinkedList(Node head) {
      
        // Dictionary to store new nodes corresponding
          // to their original nodes
        Dictionary<Node, Node> mp = new Dictionary<Node, Node>();
        Node curr = head;

        // Traverse original linked list to store new nodes
          // corresponding to original linked list
        while (curr != null) {
            mp[curr] = new Node(curr.Data);
            curr = curr.Next;
        }

        curr = head;

        // Loop to update the next and random pointers of new nodes
        while (curr != null) {
            Node newNode = mp[curr];
              if(curr.Next != null)
                newNode.Next = mp[curr.Next];
            newNode.Random = mp[curr.Random];
            curr = curr.Next;
        }

        // Return the head of the clone
        return mp[head];
    }

    // Function to print the linked list
    public static void PrintList(Node head) {
        while (head != null) {
            Console.Write(head.Data + "(");
            if (head.Random != null)
                Console.Write(head.Random.Data);
            else
                Console.Write("null");
            Console.Write(")");

            if (head.Next != null)
                Console.Write(" -> ");

            head = head.Next;
        }
        Console.WriteLine();
    }

    static void Main(string[] args) {
      
        // Creating a linked list with random pointer
        Node head = new Node(1);
        head.Next = new Node(2);
        head.Next.Next = new Node(3);
        head.Next.Next.Next = new Node(4);
        head.Next.Next.Next.Next = new Node(5);
        head.Random = head.Next.Next;
        head.Next.Random = head;
        head.Next.Next.Random = head.Next.Next.Next.Next;
        head.Next.Next.Next.Random = head.Next.Next;
        head.Next.Next.Next.Next.Random = head.Next;

        // Print the original list
        Console.WriteLine("Original linked list:");
        PrintList(head);

        // Function call
        Node clonedList = CloneLinkedList(head);

        Console.WriteLine("Cloned linked list:");
        PrintList(clonedList);
    }
}
JavaScript
// JavaScript code to Clone a linked list with next 
// and random pointer using Hashing 


class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
        this.random = null;
    }
}

// Function to clone the linked list
function cloneLinkedList(head) {
    
    // Map to store new nodes corresponding to 
    // their original nodes
    const mp = new Map();
    let curr = head;

    // Traverse original linked list to store new nodes
    // corresponding to original linked list
    while (curr !== null) {
        mp.set(curr, new Node(curr.data));
        curr = curr.next;
    }
    
    curr = head;
    
    // Loop to update the next and random pointers
    // of new nodes
    while (curr !== null) {
        const newNode = mp.get(curr);
        newNode.next = mp.get(curr.next) || null;
        newNode.random = mp.get(curr.random) || null;
        curr = curr.next;
    }
  
    // Return the head of the clone
    return mp.get(head) || null;
}

// Function to print the linked list
function printList(head) {
    let result = "";
    while (head !== null) {
        result += head.data + "(";
        result += head.random ? head.random.data : "null";
        result += ")";

        if (head.next !== null) {
            result += " -> ";
        }
        head = head.next;
    }
    console.log(result);
}


// Creating a linked list with random pointer
const head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);

head.random = head.next.next;
head.next.random = head;
head.next.next.random = head.next.next.next.next;
head.next.next.next.random = head.next.next;
head.next.next.next.next.random = head.next;

// Print the original list
console.log("Original linked list:");
printList(head);

// Function call
const clonedList = cloneLinkedList(head);

console.log("Cloned linked list:");
printList(clonedList);

Output
Original linked list:
1(3) -> 2(1) -> 3(5) -> 4(3) -> 5(2)
Cloned linked list:
1(3) -> 2(1) -> 3(5) -> 4(3) -> 5(2)

Time Complexity: O(2n), as we are traversing the linked list twice. 
Auxiliary Space: O(2n), extra O(n) space as we are using a hash table to store the new nodes.

[Naive Approach – 2] Using Hashing and Recursion- O(n) Time and O(3n) Space

The idea is to create a new node corresponding to each node in the original linked list and store the new nodes in a hash table. While traversing the original linked list we also use recursion to update the next and random pointers of new nodes corresponding to every original node.

For a more detailed solution and code checkout, this article Clone a linked list with next and random pointer using Recursion

Time Complexity: O(n) , where n is the number of nodes in linked list.
Auxiliary Space: O(3n) , extra O(n) space as we are using a hash table to store the new nodes as well for recursion stack space.

[Expected Approach] By Inserting Nodes In-place – O(3n) Time and O(1) Space

The idea is to create duplicate of a node and instead of storing in a separate hash table, we can insert it in between the original node and the next node. Now, we will have new nodes at alternate positions.

Now for a node X its duplicate will be X->next and the random pointer of the duplicate should point to X->random->next (as that is the duplicate of X->random). So, iterate over the entire linked list to update the random pointer of all the cloned nodes and then iterate again to separate the original linked list and the cloned linked list.

Illustration:


Follow the steps mentioned below to implement the idea:

  • Create the copy of node 1 and insert it between node 1 and node 2 in the original Linked List, create the copy of node 2 and insert it between 2nd and 3rd node and so on. Add the copy of N after the Nth node 
  • Connect the clone node by updating the random pointers.
  • Separate the cloned linked list from the original list by updating the next pointers. 
C++
// C++ code to Clone a linked list with next and random
// pointer by Inserting Nodes In-place

#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    Node *next, *random;
    Node(int x) {
        data = x;
        next = random = NULL;
    }
};

Node* cloneLinkedList(Node* head) {
    if (head == NULL) {
        return NULL;
    }
    
    // Create new nodes and insert them next to 
      // the original nodes
    Node* curr = head;
    while (curr != NULL) {
        Node* newNode = new Node(curr->data);
        newNode->next = curr->next;
        curr->next = newNode;
        curr = newNode->next;
    }
    
    // Set the random pointers of the new nodes
    curr = head;
    while (curr != NULL) {
        if (curr->random != NULL)
            curr->next->random = curr->random->next;
        curr = curr->next->next;
    }
    
    // Separate the new nodes from the original nodes
    curr = head;
    Node* clonedHead = head->next;
    Node* clone = clonedHead;
    while (clone->next != NULL) {
          
          // Update the next nodes of original node 
          // and cloned node
        curr->next = curr->next->next;
        clone->next = clone->next->next;
          
          // Move pointers of original as well as  
          // cloned linked list to their next nodes
        curr = curr->next;
        clone = clone->next;
    }
    curr->next = NULL;
    clone->next = NULL;
    
    return clonedHead;
}


// Function to print the linked list
void printList(Node* head) {
    while (head != NULL) {
        cout << head->data << "(";
          if(head->random)
              cout << head->random->data << ")";
          else 
              cout << "null" << ")";
        
          if(head->next != NULL)
              cout << " -> ";
        head = head->next;
    }
    cout << endl;
}

int main() {
  
    // Creating a linked list with random pointer
    Node* head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(3);
    head->next->next->next = new Node(4);
    head->next->next->next->next = new Node(5);
    head->random = head->next->next;
    head->next->random = head;
    head->next->next->random = head->next->next->next->next;
    head->next->next->next->random = head->next->next;
    head->next->next->next->next->random = head->next;
  
    // Print the original list
    cout << "Original linked list:\n";
    printList(head);
  
    // Function call
    Node* clonedList = cloneLinkedList(head);
  
    cout << "Cloned linked list:\n";
    printList(clonedList);
  
    return 0;
}
Java
// Java code to Clone a linked list with next and random
// pointer by Inserting Nodes In-place

class Node {
    int data;
    Node next, random;
    
    Node(int x) {
        data = x;
        next = random = null;
    }
}

class GfG {
    
    // Function to clone the linked list
    static Node cloneLinkedList(Node head) {
        if (head == null) {
            return null;
        }
        
        // Create new nodes and insert them next to the original nodes
        Node curr = head;
        while (curr != null) {
            Node newNode = new Node(curr.data);
            newNode.next = curr.next;
            curr.next = newNode;
            curr = newNode.next;
        }
        
        // Set the random pointers of the new nodes
        curr = head;
        while (curr != null) {
            if (curr.random != null) {
                curr.next.random = curr.random.next;
            }
            curr = curr.next.next;
        }
        
        // Separate the new nodes from the original nodes
        curr = head;
        Node clonedHead = head.next;
        Node clone = clonedHead;
        while (clone.next != null) {
            // Update the next nodes of original node
              // and cloned node
            curr.next = curr.next.next;
            clone.next = clone.next.next;
            
            // Move pointers of original and cloned
              // linked list to their next nodes
            curr = curr.next;
            clone = clone.next;
        }
        curr.next = null;
        clone.next = null;
        
        return clonedHead;
    }
    
    // Function to print the linked list
    public static void printList(Node head) {
        while (head != null) {
            System.out.print(head.data + "(");
            if (head.random != null) {
                System.out.print(head.random.data);
            } else {
                System.out.print("null");
            }
            System.out.print(")");
            
            if (head.next != null) {
                System.out.print(" -> ");
            }
            head = head.next;
        }
        System.out.println();
    }
    
    public static void main(String[] args) {
          
        // Creating a linked list with random pointer
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);
        head.random = head.next.next;
        head.next.random = head;
        head.next.next.random = head.next.next.next.next;
        head.next.next.next.random = head.next.next;
        head.next.next.next.next.random = head.next;
        
        // Print the original list
        System.out.println("Original linked list:");
        printList(head);
        
        // Function call
        Node clonedList = cloneLinkedList(head);
        
        System.out.println("Cloned linked list:");
        printList(clonedList);
    }
}
Python
# Python code to Clone a linked list with next and random
# pointer by Inserting Nodes In-place

class Node:
    def __init__(self, x):
        self.data = x
        self.next = None
        self.random = None

# Function to clone the linked list
def clone_linked_list(head):
    if head is None:
        return None
    
    # Create new nodes and insert them next to 
    # the original nodes
    curr = head
    while curr is not None:
        new_node = Node(curr.data)
        new_node.next = curr.next
        curr.next = new_node
        curr = new_node.next
    
    # Set the random pointers of the new nodes
    curr = head
    while curr is not None:
        if curr.random is not None:
            curr.next.random = curr.random.next
        curr = curr.next.next
    
    # Separate the new nodes from the original nodes
    curr = head
    cloned_head = head.next
    clone = cloned_head
    while clone.next is not None:
        # Update the next nodes of original node 
        # and cloned node
        curr.next = curr.next.next
        clone.next = clone.next.next
        
        # Move pointers of original as well as  
        # cloned linked list to their next nodes
        curr = curr.next
        clone = clone.next
    curr.next = None
    clone.next = None
    
    return cloned_head

# Function to print the linked list
def print_list(head):
    while head is not None:
        print(f"{head.data}(", end="")
        if head.random:
            print(f"{head.random.data})", end="")
        else:
            print("null)", end="")
        
        if head.next is not None:
            print(" -> ", end="")
        head = head.next
    print()

if __name__ == "__main__":
  
    # Creating a linked list with random pointer
    head = Node(1)
    head.next = Node(2)
    head.next.next = Node(3)
    head.next.next.next = Node(4)
    head.next.next.next.next = Node(5)
    head.random = head.next.next
    head.next.random = head
    head.next.next.random = head.next.next.next.next
    head.next.next.next.random = head.next.next
    head.next.next.next.next.random = head.next
    
    # Print the original list
    print("Original linked list:")
    print_list(head)
    
    # Function call
    cloned_list = clone_linked_list(head)
    
    print("Cloned linked list:")
    print_list(cloned_list)
C#
// C# code to Clone a linked list with next and random
// pointer by Inserting Nodes In-place

using System;
using System.Collections.Generic;

public class Node {
    public int Data;
    public Node Next, Random;

    public Node(int x) {
        Data = x;
        Next = Random = null;
    }
}

public class GfG {
    public static Node CloneLinkedList(Node head) {
        if (head == null)
            return null;

        // Create new nodes and insert them next to 
        // the original nodes
        Node curr = head;
        while (curr != null) {
            Node newNode = new Node(curr.Data);
            newNode.Next = curr.Next;
            curr.Next = newNode;
            curr = newNode.Next;
        }

        // Set the random pointers of the new nodes
        curr = head;
        while (curr != null) {
            if (curr.Random != null)
                curr.Next.Random = curr.Random.Next;
            curr = curr.Next.Next;
        }

        // Separate the new nodes from the original nodes
        curr = head;
        Node clonedHead = head.Next;
        Node clone = clonedHead;
        while (clone.Next != null) {
          
            // Update the next nodes of original node 
            // and cloned node
            curr.Next = curr.Next.Next;
            clone.Next = clone.Next.Next;

            // Move pointers of original as well as  
            // cloned linked list to their next nodes
            curr = curr.Next;
            clone = clone.Next;
        }
        curr.Next = null;
        clone.Next = null;

        return clonedHead;
    }

    // Function to print the linked list
    public static void PrintList(Node head) {
        while (head != null) {
            Console.Write(head.Data + "(");
            if (head.Random != null)
                Console.Write(head.Random.Data + ")");
            else
                Console.Write("null)");
            

            if (head.Next != null)
                Console.Write(" -> ");
            head = head.Next;
        }
        Console.WriteLine();
    }

    public static void Main() {
      
        // Creating a linked list with random pointer
        Node head = new Node(1);
        head.Next = new Node(2);
        head.Next.Next = new Node(3);
        head.Next.Next.Next = new Node(4);
        head.Next.Next.Next.Next = new Node(5);
        head.Random = head.Next.Next;
        head.Next.Random = head;
        head.Next.Next.Random = head.Next.Next.Next.Next;
        head.Next.Next.Next.Random = head.Next.Next;
        head.Next.Next.Next.Next.Random = head.Next;

        // Print the original list
        Console.WriteLine("Original linked list:");
        PrintList(head);

        Node clonedList = CloneLinkedList(head);

        Console.WriteLine("Cloned linked list:");
        PrintList(clonedList);
    }
}
JavaScript
// JavaScript code to Clone a linked list with next and random
// pointer by Inserting Nodes In-place

class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
        this.random = null;
    }
}

function cloneLinkedList(head) {
    if (head === null) {
        return null;
    }

    // Create new nodes and insert them next to the 
    // original nodes
    let curr = head;
    while (curr !== null) {
        let newNode = new Node(curr.data);
        newNode.next = curr.next;
        curr.next = newNode;
        curr = newNode.next;
    }

    // Set the random pointers of the new nodes
    curr = head;
    while (curr !== null) {
        if (curr.random !== null) {
            curr.next.random = curr.random.next;
        }
        curr = curr.next.next;
    }

    // Separate the new nodes from the original nodes
    curr = head;
    let clonedHead = head.next;
    let clone = clonedHead;
    while (clone.next !== null) {
    
        // Update the next nodes of original node and cloned node
        curr.next = curr.next.next;
        clone.next = clone.next.next;

        // Move pointers of original as well as cloned
        // linked list to their next nodes
        curr = curr.next;
        clone = clone.next;
    }
    curr.next = null;
    clone.next = null;

    return clonedHead;
}

// Function to print the linked list
function printList(head) {
    let result = "";
    while (head !== null) {
        result += head.data + "(";
        result += head.random ? head.random.data : "null";
        result += ")";

        if (head.next !== null) {
            result += " -> ";
        }
        head = head.next;
    }
    console.log(result);
}

// Creating a linked list with random pointer
let head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
head.random = head.next.next;
head.next.random = head;
head.next.next.random = head.next.next.next.next;
head.next.next.next.random = head.next.next;
head.next.next.next.next.random = head.next;

// Print the original list
console.log("Original linked list:");
printList(head);

let clonedList = cloneLinkedList(head);

console.log("Cloned linked list:");
printList(clonedList);

Output
Original linked list:
1(3) -> 2(1) -> 3(5) -> 4(3) -> 5(2)
Cloned linked list:
1(3) -> 2(1) -> 3(5) -> 4(3) -> 5(2)

Time Complexity: O(3n), because we are traversing the linked list three times. 
Auxiliary Space: O(1), as we are storing all the cloned nodes in the original linked list itself, no extra space is required.



Similar Reads

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 ident
10 min read
Clone a linked list with next and random pointer using Recursion
Given a linked list of size n where each node has two links: next pointer pointing to the next node and random pointer to any random node in the list. The task is to create a clone of this linked list. Approach : The idea is to create a new node corresponding to each node in the original linked list and store the new nodes in a hash table. While tr
8 min read
Javascript Program For Cloning 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 iden
4 min read
Javascript Program For Cloning A Linked List With Next And Random Pointer- Set 2
We have already discussed 2 different ways to clone a linked list. In this post, one more simple method to clone a linked list is discussed. The idea is to use Hashing. Below is an algorithm. Traverse the original linked list and make a copy in terms of data.Make a hash map of key-value pair with the original linked list node and copy linked list n
3 min read
How to create a pointer to another pointer in a linked list?
In this article we cover how to create a pointer to another pointer in a linked list, it can be singly, doubly, or circularly. What is Linked List: A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image: Singly
7 min read
Insertion in a sorted circular linked list when a random pointer is given
Given an array arr[] of integers and a pointer to a random node of a circular sorted linked list (initially empty), the task is to insert all the elements of arr[] into the circular linked list. Examples: Input: arr[] = {12, 56, 2, 11, 1, 90} Output: 1 2 11 12 56 90 Input: arr[] = {6, 2, 78, 45, 200} Output: 2 6 45 78 200 Approach: We are given a r
12 min read
Point to next higher value node in a linked list with an arbitrary pointer
Given singly linked list with every node having an additional "arbitrary" pointer that currently points to NULL. Need to make the "arbitrary" pointer point to the next higher value node. We strongly recommend to minimize your browser and try this yourself first A Simple Solution is to traverse all nodes one by one, for every node, find the node whi
15+ min read
Javascript Program For Pointing To Next Higher Value Node In A Linked List With An Arbitrary Pointer
Given singly linked list with every node having an additional "arbitrary" pointer that currently points to NULL. Need to make the "arbitrary" pointer point to the next higher-value node. We strongly recommend to minimize your browser and try this yourself first A Simple Solution is to traverse all nodes one by one, for every node, find the node whi
4 min read
Clone a Binary Tree with Random Pointers
Given a Binary Tree where every node has the following structure. struct node { int key; struct node *left,*right,*random;} The random pointer points to any random node of the binary tree and can even point to NULL, clone the given binary tree. Recommended PracticeClone a Binary TreeTry It!Method 1 (Use Hashing): The idea is to store a mapping from
11 min read
How to write C functions that modify head pointer of a Linked List?
Consider simple representation (without any dummy node) of Linked List. Functions that operate on such Linked lists can be divided into two categories: 1) Functions that do not modify the head pointer: Examples of such functions include, printing a linked list, updating data members of nodes like adding given a value to all nodes, or some other ope
4 min read
Given only a pointer/reference to a node to be deleted in a singly linked list, how do you delete it?
Given a pointer to a node to be deleted, delete the node. Note that we don't have a pointer to the head node. Recommended PracticeDelete nodes having greater value on rightTry It!A simple solution is to traverse the linked list until you find the node you want to delete. But this solution requires a pointer to the head node, which contradicts the p
8 min read
Point arbit pointer to greatest value right side node in a linked list
Given singly linked list with every node having an additional “arbitrary” pointer that currently points to NULL. We need to make the “arbitrary” pointer to the greatest value node in a linked list on its right side. A Simple Solution is to traverse all nodes one by one. For every node, find the node which has the greatest value on the right side an
15+ min read
Delete multiple occurrences of key in Linked list using double pointer
Given a singly linked list, delete all occurrences of a given key in it. For example, consider the following list. Input: 2 -> 2 -> 4 -> 3 -> 2 Key to delete = 2Output: 4 -> 3 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.This is mainly an alternative of this post which deletes multiple occurrence
6 min read
Two-Pointer Technique in a Linked List
The two-pointer technique is a common technique used in linked list problems to solve a variety of problems efficiently. It involves using two pointers that traverse the linked list at different speeds or in different directions. Use Cases of Two-Pointer Technique in a Linked List:1. Finding the Middle of a Linked List:One common application of the
3 min read
Javascript Program For Pointing Arbit Pointer To Greatest Value Right Side Node In A Linked List
Given singly linked list with every node having an additional “arbitrary” pointer that currently points to NULL. We need to make the “arbitrary” pointer to the greatest value node in a linked list on its right side. A Simple Solution is to traverse all nodes one by one. For every node, find the node which has the greatest value on the right side an
5 min read
Delete a Node in a Singly Linked List with Only a Pointer
Given only a pointer to a node to be deleted in a singly linked list. The task is to delete that node from the list. Note: The given pointer does not point to the last node of the linked list. Examples: Input: LinkedList: 1->2->3->4->5, delete_ptr = 2Output: LinkedList: 1->3->4->5 Input: LinkedList: 1->2->3->4->5, d
6 min read
Test Case Generation | Set 2 ( Random Characters, Strings and Arrays of Random Strings)
Set 1 (Random Numbers, Arrays and Matrices) Generating Random Characters C/C++ Code // A C++ Program to generate test cases for // random characters #include<bits/stdc++.h> using namespace std; // Define the number of runs for the test data // generated #define RUN 5 // Define the range of the test data generated // Here it is 'a' to 'z' #def
11 min read
Implement random-0-6-Generator using the given random-0-1-Generator
Given a function random01Generator() that gives you randomly either 0 or 1, implement a function that utilizes this function and generate numbers between 0 and 6(both inclusive). All numbers should have same probabilities of occurrence. Examples: on multiple runs, it gives 3 2 3 6 0 Approach : The idea here is to find the range of the smallest numb
5 min read
Select a Random Node from a Singly Linked List
Given a singly linked list, select a random node from the linked list (the probability of picking a node should be 1/N if there are N nodes in the list). You are given a random number generator.Below is a Simple Solution Count the number of nodes by traversing the list. Traverse the list again and select every node with a probability of 1/N. The se
15 min read
Javascript Program For Selecting A Random Node From A Singly Linked List
Given a singly linked list, select a random node from the linked list (the probability of picking a node should be 1/N if there are N nodes in the list). You are given a random number generator. Below is a Simple Solution: Count the number of nodes by traversing the list.Traverse the list again and select every node with probability 1/N. The select
4 min read
Is two way linked list and doubly linked list same?
Yes, a two-way linked list and a doubly linked list are the same. Both terms refer to a type of linked list where each node contains a reference to the next node as well as the previous node in the sequence. The term “two-way” emphasizes the ability to move in both directions through the list, while “doubly” highlights that there are two links per
3 min read
Difference between Singly linked list and Doubly linked list
Introduction to Singly linked list : A singly linked list is a set of nodes where each node has two fields 'data' and 'link'. The 'data' field stores actual piece of information and 'link' field is used to point to next node. Basically the 'link' field stores the address of the next node.  Introduction to Doubly linked list : A Doubly Linked List (
2 min read
Convert Singly Linked List to XOR Linked List
Prerequisite: XOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2 An XOR linked list is a memory efficient doubly linked list in which the next pointer of every node stores the XOR of previous and next node's address. Given a singly linked list, the task is to convert the gi
9 min read
XOR linked list- Remove first node of the linked list
Given an XOR linked list, the task is to remove the first node of the XOR linked list. Examples: Input: XLL = 4 < – > 7 < – > 9 < – > 7 Output: 7 < – > 9 < – > 7 Explanation: Removing the first node of the XOR linked list modifies XLL to 7 < – > 9 < – > 7 Input: XLL = NULL Output: List Is Empty Approach: Th
11 min read
Remove all occurrences of one Linked list in another Linked list
Given two linked lists head1 and head2, the task is to remove all occurrences of head2 in head1 and return the head1. Examples: Input: head1 = 2 -> 3 -> 4 -> 5 -> 3 -> 4, head2 = 3 -> 4Output: 2 -> 5Explanation: After removing all occurrences of 3 -> 4 in head1 output is 2 -> 5. Input: head1 = 3 -> 6 -> 9 -> 8 -
9 min read
Count occurrences of one linked list in another Linked List
Given two linked lists head1 and head2, the task is to find occurrences of head2 in head1. Examples: Input: Head1 = 1->2->3->2->4->5->2->4, Head2 = 2->4Output: Occurrences of head2 in head1: 2 Input: Head1 = 3->4->1->5->2, Head2 = 3->4Output: Occurrences of Head2 in Head1: 1 Approach 1: To solve the problem us
15 min read
When is Doubly Linked List more Efficient than Singly Linked List?
Did you know there are some cases where a Doubly Linked List is more efficient than a Singly Linked List, even though it takes more memory compared to a Singly Linked List? What are those Cases? Well, we will discuss that in the following article, But first, let's talk about Singly and linked lists: What is a Singly Linked List?A singly linked list
4 min read
XOR Linked List - Reverse a Linked List in groups of given size
Given a XOR linked list and an integer K, the task is to reverse every K nodes in the given XOR linked list. Examples: Input: XLL = 7< – > 6 < – > 8 < – > 11 < – > 3, K = 3 Output: 8 < – > 6 < – > 7 < – > 3 < – > 11 Explanation: Reversing first K(= 3) nodes modifies the Linked List to 8 < – > 6
13 min read
XOR Linked List: Remove last node of the Linked List
Given an XOR linked list, the task is to delete the node at the end of the XOR Linked List. Examples: Input: 4<–>7<–>9<–>7Output: 4<–>7<–>9Explanation: Deleting a node from the end modifies the given XOR Linked List to 4<–>7<–>9 Input: 10Output: List is emptyExplanation: After deleting the only node present
15+ min read
XOR Linked List - Pairwise swap elements of a given linked list
Given a XOR linked list, the task is to pairwise swap the elements of the given XOR linked list . Examples: Input: 4 <-> 7 <-> 9 <-> 7Output: 7 <-> 4 <-> 7 <-> 9Explanation:First pair of nodes are swapped to formed the sequence {4, 7} and second pair of nodes are swapped to form the sequence {9, 7}. Input: 1 <
12 min read