在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)
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便