# Correct the Random Pointer in Doubly Linked List in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

In this tutorial, we will be discussing a program to correct the random pointer in a doubly linked list.

For this we will be provided with a doubly linked list with one node having a random pointer. Our task is to rectify the element to whom the pointer should be pointing i.e the element next to it.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
//node structure for doubly linked list
struct node {
int data;
node* next;
node* prev;
};
//new node creation
node* newNode(int data){
node* temp = new node;
temp->data = data;
temp->next = temp->prev = NULL;
return temp;
}
//correcting the random pointer
return;
node* temp = head;
return;
}
//changing if the position is incorrect
if (head->prev != NULL) {
return;
}
temp = temp->next;
while (temp) {
if (temp->next && temp->next->prev != temp) {
temp->next->prev = temp;
return;
}
else if (temp->prev && temp->prev->next != temp) {
temp->prev->next = temp;
return;
}
temp = temp->next;
}
}
//printing the doubly linked list
void printList(node* head) {
node* temp = head;
while (temp) {
cout << temp->data << " (";
cout << (temp->prev ? temp->prev->data : -1)<< ") ";
temp = temp->next;
}
cout << endl;
}
int main(){
node* head = newNode(1);
cout << "\nIncorrect Linked List: ";
}
Incorrect Linked List: 1 (-1) 2 (1) 3 (1) 4 (3)
Corrected Linked List: 1 (-1) 2 (1) 3 (2) 4 (3)