इस ट्यूटोरियल में, हम डौबली लिंक्ड लिस्ट में रैंडम पॉइंटर को सही करने के लिए एक प्रोग्राम पर चर्चा करेंगे।
इसके लिए हमें एक डौबली लिंक्ड लिस्ट प्रदान की जाएगी जिसमें एक नोड का रैंडम पॉइंटर होगा। हमारा कार्य उस एलिमेंट को ठीक करना है जिसे पॉइंटर को इंगित करना चाहिए यानी उसके बगल का एलिमेंट।
उदाहरण
#include <bits/stdc++.h> using namespace std; //डौबली लिंक्ड लिस्ट के लिए नोड संरचना struct node { int data; node* next; node* prev; }; //नया नोड बनाना node* newNode(int data){ node* temp = new node; temp->data = data; temp->next = temp->prev = NULL; return temp; } //रैंडम पॉइंटर को सही करना void get_cpointer(node*& head){ if (!head) return; node* temp = head; if (head->next && head->next->prev != head) { head->next->prev = head; return; } //स्थिति गलत होने पर बदलना if (head->prev != NULL) { 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; } } //डौबली लिंक्ड लिस्ट प्रिंट करना 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); 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; cout << "\nIncorrect Linked List: "; printList(head); get_cpointer(head); cout << "\nCorrected Linked List: "; printList(head); return 0; }आउटपुट
Incorrect Linked List: 1 (-1) 2 (1) 3 (1) 4 (3) Corrected Linked List: 1 (-1) 2 (1) 3 (2) 4 (3)