用 C++ 修正雙向連結串列中的隨機指標
在本教程中,我們將討論一個程式,用來修正雙向連結串列中的隨機指標。
為此,我們將使用一個雙向連結串列,其中一個節點具有隨機指標。我們的任務是糾正元素指向另一個元素,即它旁邊的元素。
舉例
#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
void get_cpointer(node*& head){
if (!head)
return;
node* temp = head;
if (head->next && head->next->prev != head) {
head->next->prev = head;
return;
}
//changing if the position is incorrect
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;
}
}
//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);
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)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP