Open In App

Correct the Random Pointer in Doubly Linked List

Last Updated : 13 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a doubly linked list having exactly one of the node pointing to a random node in the list, the task is to correct this random pointer in the doubly linked list, such that it points to the expected node.
Examples: 
 

Input: 

Output: 

Explanation: 2’s next pointer has been corrected to point to 3. Earlier it was pointing to 1, which was incorrect. 
 

Approach: This can be achieved by simply iterating the list and checking the individual pointers.
Below is the implementation for the above approach:
 

C++




// C++ program to Correct
// the Random Pointer in Doubly Linked List
#include<iostream>
using namespace std;
 
// Node of a doubly linked list
class Node
{
    public:
    int data;
    // Pointer to next node in DLL
    Node *next;
       
      // Pointer to previous node in DLL
    Node *prev;
 
    Node():prev(NULL),next(NULL){}
    Node(int data):data(data),prev(NULL),next(NULL){}
 
};
class doublell
{
    public:
    Node *head;
    // Function to append node in the DLL
    void appendNode(Node *n)
    {
        Node *temp=head;
        if(temp==NULL)
        {
            head=n;
             
        }
        else
        {
            while(temp->next!=NULL)
            {
                temp=temp->next;
            }
            temp->next=n;
            n->prev=temp;
        }
    }
      // Function to print the DLL
    void print()
    {
        Node *temp=head;
        while(temp!=NULL)
        {
            cout<<temp->data<<"->";
            temp=temp->next;
        }
        cout<<endl;
    }
      // Function to print reverse of the DLL
    void printReverse()
    {
        Node *temp=head;
        while(temp->next!=NULL)
        {
            temp=temp->next;
        }
        while(temp!=NULL)
        {
            cout<<temp->data<<" ->";
            temp=temp->prev;
        }
        cout<<endl;
    }
    // Function to correct the random pointer
    void correctPointer()
    {
        if(!head)
        {
            return;
        }
        Node *temp=head;
        while(temp->next!=NULL)
        {
            if(temp->next->prev!=temp)
            {
                temp->next->prev=temp;
            }
            temp=temp->next;
        }
    }
};
 
// Driver Code
int main()
{
   
    // Creating a DLL
    doublell ll;
    ll.head = new Node(1);
    ll.head->next = new Node(2);
    ll.head->next->prev = ll.head;
    ll.head->next->next = new Node(3);
    ll.head->next->next->prev =ll.head;
    ll.head->next->next->next = new Node(4);
    ll.head->next->next->next->prev = ll.head->next->next;
   
    cout << "\nIncorrect Linked List: ";
    ll.print();
    ll.printReverse();
   
    ll.correctPointer();
   
    cout << "\nCorrected Linked List: ";
    ll.print();
    ll.printReverse();
 
   
    return 0;
}


Java




// Java program to Correct
// the Random Pointer in Doubly Linked List
class GFG
{
 
// Node of a doubly linked list
static class node
{
    int data;
 
    // Pointer to next node in DLL
    node next;
 
    // Pointer to previous node in DLL
    node prev;
};
 
// Function to allocate node
static node newNode(int data)
{
    node temp = new node();
    temp.data = data;
    temp.next = temp.prev = null;
    return temp;
}
 
// Function to correct the random pointer
static void correctPointer(node head)
{
    if (head == null)
        return;
 
    node temp = head;
 
    // if head->next's previous is not
    // pointing to head itself,
    // change it.
    if (head.next != null &&
        head.next.prev != head)
    {
        head.next.prev = head;
        return;
    }
 
    // If head's previous pointer is incorrect,
    // change it.
    if (head.prev != null)
    {
        head.prev = null;
        return;
    }
 
    // Else check for remaining nodes.
    temp = temp.next;
    while (temp != null)
    {
 
        // If node.next's previous pointer is
        // incorrect, change it.
        if (temp.next != null &&
            temp.next.prev != temp)
        {
            temp.next.prev = temp;
            return;
        }
 
        // Else If node.prev's next pointer is
        // incorrect, change it.
        else if (temp.prev != null &&
                 temp.prev.next != temp)
        {
            temp.prev.next = temp;
            return;
        }
        System.out.print("");
         
        // Else iterate on remaining.
        temp = temp.next;
    }
}
 
// Function to print the DLL
static void printList(node head)
{
    node temp = head;
 
    while (temp != null)
    {
 
        System.out.print(temp.data + " (");
 
        // If prev pointer is null, print -1.
        System.out.print((temp.prev != null ?
                          temp.prev.data: -1) + ") ");
 
        temp = temp.next;
    }
    System.out.print("\n");
}
 
// Driver Code
public static void main(String[] args)
{
    // Creating a DLL
    node head = newNode(1);
    head.next = newNode(2);
    head.next.prev = head;
    head.next.next = newNode(3);
    head.next.next.prev = head;
    head.next.next.next = newNode(4);
    head.next.next.next.prev = head.next.next;
 
    System.out.print("\nIncorrect Linked List: ");
    printList(head);
 
    correctPointer(head);
 
    System.out.print("\nCorrected Linked List: ");
    printList(head);
}
}
 
// This code is contributed by Princi Singh


Python3




# Python3 program to Correct the
# Random Pointer in Doubly Linked List
 
class Node:
     
    def __init__(self, data):
        self.data = data
        self.prev = None
        self.next = None
 
# Function to correct the random pointer
def correctPointer(head):
 
    if head == None:
        return
 
    temp = head
 
    # if head.next's previous is not
    # pointing to head itself, change it.
    if (head.next != None and
        head.next.prev != head):
 
        head.next.prev = head
        return
     
    # If head's previous pointer is
    # incorrect, change it.
    if head.prev != None:
 
        head.prev = None
        return
     
    # Else check for remaining nodes.
    temp = temp.next
    while temp != None:
 
        # If node.next's previous pointer
        # is incorrect, change it.
        if (temp.next != None and
            temp.next.prev != temp):
 
            temp.next.prev = temp
            return
         
        # Else If node.prev's next pointer
        # is incorrect, change it.
        elif (temp.prev != None and
              temp.prev.next != temp):
 
            temp.prev.next = temp
            return
         
        # Else iterate on remaining.
        temp = temp.next
     
# Function to print the DLL
def printList(head):
 
    temp = head
 
    while temp != None:
 
        print(temp.data, "(", end = "")
 
        # If prev pointer is null, print -1.
        if temp.prev == None:
            print(-1, end = ") ")
        else:
            print(temp.prev.data, end = ") ")
         
        temp = temp.next
     
    print()
 
# Driver Code
if __name__ == "__main__":
 
    # Creating a DLL
    head = Node(1)
    head.next = Node(2)
    head.next.prev = head
    head.next.next = Node(3)
    head.next.next.prev = head
    head.next.next.next = Node(4)
    head.next.next.next.prev = head.next.next
 
    print("Incorrect Linked List:",
                         end = " ")
    printList(head)
 
    correctPointer(head)
 
    print("\nCorrected Linked List:",
                           end = " ")
    printList(head)
 
# This code is contributed
# by Rituraj Jain


C#




// C# program to Correct the
// Random Pointer in Doubly Linked List
using System;
class GFG
{
 
// Node of a doubly linked list
class node
{
    public int data;
 
    // Pointer to next node in DLL
    public node next;
 
    // Pointer to next node in DLL
    public node prev;
};
 
// Function to allocate node
static node newNode(int data)
{
    node temp = new node();
    temp.data = data;
    temp.next = temp.prev = null;
    return temp;
}
 
// Function to correct the random pointer
static void correctPointer(node head)
{
    if (head == null)
        return;
 
    node temp = head;
 
    // if head->next's previous is not
    // pointing to head itself,
    // change it.
    if (head.next != null &&
        head.next.prev != head)
    {
        head.next.prev = head;
        return;
    }
 
    // If head's previous pointer is incorrect,
    // change it.
    if (head.prev != null)
    {
        head.prev = null;
        return;
    }
 
    // Else check for remaining nodes.
    temp = temp.next;
    while (temp != null)
    {
 
        // If node.next's previous pointer is
        // incorrect, change it.
        if (temp.next != null &&
            temp.next.prev != temp)
        {
            temp.next.prev = temp;
            return;
        }
 
        // Else If node.prev's next pointer
        // is incorrect, change it.
        else if (temp.prev != null &&
                 temp.prev.next != temp)
        {
            temp.prev.next = temp;
            return;
        }
        Console.Write("");
         
        // Else iterate on remaining.
        temp = temp.next;
    }
}
 
// Function to print the DLL
static void printList(node head)
{
    node temp = head;
 
    while (temp != null)
    {
        Console.Write(temp.data + " (");
 
        // If prev pointer is null, print -1.
        Console.Write((temp.prev != null ?
                       temp.prev.data: -1) + ") ");
 
        temp = temp.next;
    }
    Console.Write("\n");
}
 
// Driver Code
public static void Main(String[] args)
{
    // Creating a DLL
    node head = newNode(1);
    head.next = newNode(2);
    head.next.prev = head;
    head.next.next = newNode(3);
    head.next.next.prev = head;
    head.next.next.next = newNode(4);
    head.next.next.next.prev = head.next.next;
 
    Console.Write("\nIncorrect Linked List: ");
    printList(head);
 
    correctPointer(head);
 
    Console.Write("\nCorrected Linked List: ");
    printList(head);
}
}
 
// This code is contributed by PrinciRaj1992


Javascript




// Node of a doubly linked list
class Node {
    constructor(data) {
        this.data = data;
        this.prev = null;
        this.next = null;
    }
}
 
class doublell {
    constructor() {
        this.head = null;
    }
 
    // Function to append node in the DLL
    appendNode(n) {
        let temp = this.head;
        if (!temp) {
            this.head = n;
        } else {
            while (temp.next) {
                temp = temp.next;
            }
            temp.next = n;
            n.prev = temp;
        }
    }
 
    // Function to print the DLL in a single line
    print() {
        let temp = this.head;
        let result = "";
        while (temp) {
            result += temp.data + " -> ";
            temp = temp.next;
        }
        console.log(result);
    }
 
    // Function to print reverse of the DLL in a single line
    printReverse() {
        let temp = this.head;
        while (temp && temp.next) {
            temp = temp.next;
        }
        let result = "";
        while (temp) {
            result += temp.data + " -> ";
            temp = temp.prev;
        }
        console.log(result);
    }
 
    // Function to correct the random pointer
    correctPointer() {
        if (!this.head) {
            return;
        }
        let temp = this.head;
        while (temp.next) {
            if (temp.next.prev !== temp) {
                temp.next.prev = temp;
            }
            temp = temp.next;
        }
    }
}
 
// Creating a DLL
const ll = new doublell();
ll.head = new Node(1);
ll.head.next = new Node(2);
ll.head.next.prev = ll.head;
ll.head.next.next = new Node(3);
ll.head.next.next.prev = ll.head;
ll.head.next.next.next = new Node(4);
ll.head.next.next.next.prev = ll.head.next.next;
 
console.log("\nIncorrect Linked List: ");
ll.print();
ll.printReverse();
ll.correctPointer();
 
console.log("\nCorrected Linked List: ");
ll.print();
ll.printReverse();


Output

Incorrect Linked List: 1 (-1) 2 (1) 3 (1) 4 (3) 

Corrected Linked List: 1 (-1) 2 (1) 3 (2) 4 (3)

Time Complexity: O(n)

Auxiliary Space: O(n)



Similar Reads

Difference between passing pointer to pointer and address of pointer to any function
In this article, the differences between passing “pointer to pointer” and “address of pointer” to a function. In C or C++ Programming Language, it is known that pointers hold the address of the variables or any memory location. If pointers are pointed to the memory location, it can be used to change the value of the variable. As for functions, any
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: [capti
7 min read
RGYB(color) Slots Game to guess the correct color for the correct slot
Given that you have four slots, and each slot will contain a color red (R), yellow (Y), green (G), blue (B) respectively. For example, if you select YGGR (Slot-1 is yellow, Slots-2 and -3 are green, Slot -4 is red). The colors of slots are not known to you beforehand. You will make a guess about the colors. You might, for example, guess YRGB. When
9 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
Java 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 ident
4 min read
Python 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 ident
4 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 ident
4 min read
Clone a Linked List with next and Random Pointer
Given a linked list of size N where each node has two links: one pointer points to the next node and the second pointer points to any node in the list. The task is to create a clone of this linked list in O(N) time. Note: The pointer pointing to the next node is 'next' pointer and the one pointing to an arbitrary node is called 'arbit' pointer as i
17 min read
Clone 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. Recommended PracticeClone a linked list with next and random pointerTry It! The idea is to use Hashing. Below is algorithm. Traverse the original linked list and make a copy in terms of data. Make a hash map o
11 min read
C++ 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. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. The idea is to use Hashing. Below is algorithm.  Traverse the original linked list and make a copy in terms of data. Make a h
4 min read
Article Tags :
Practice Tags :