在 C++ 中将随机指针指向链表右侧的最大值节点
在这个问题中,给定一个带值、链接指针和任意指针的链表。我们的任务是让任意指针指向链表中其右侧的最大值。
我们举一个例子来理解这个问题,
在这里,我们可以看到链表的以下任意指针,指向链表右侧的最大元素。
12 -> 76, 76 -> 54, 54 -> 8, 8 -> 41
为了解决这个问题,我们需要找到节点右侧的最大元素。为此,我们将反向遍历链表,开始找到所有最大元素,然后在每个节点,我们的任意点指向我们维护的最大节点。
示例
程序展示了我们解决方案的实现,
#include<bits/stdc++.h> using namespace std; struct Node{ int data; Node* next, *arbitrary; }; Node* reverseList(Node *head){ Node *prev = NULL, *current = head, *next; while (current != NULL){ next = current->next; current->next = prev; prev = current; current = next; } return prev; } Node* populateArbitraray(Node *head){ head = reverseList(head); Node *max = head; Node *temp = head->next; while (temp != NULL){ temp->arbitrary = max; if (max->data < temp->data) max = temp; temp = temp->next; } return reverseList(head); } Node *insertNode(int data) { Node *new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node; } int main() { Node *head = insertNode(12); head->next = insertNode(76); head->next->next = insertNode(54); head->next->next->next = insertNode(8); head->next->next->next->next = insertNode(41); head = populateArbitraray(head); printf("Linked List with Arbitrary Pointer: \n"); while (head!=NULL){ cout<<head->data<<"->"; if (head->next) cout<<head->next->data; else cout<<"NULL"; cout<<": "<<head->data<<"->"; if (head->arbitrary) cout<<head->arbitrary->data; else cout<<"NULL"; cout << endl; head = head->next; } return 0; }
输出
Linked List with Arbitrary Pointer: 12->76: 12->76 76->54: 76->54 54->8: 54->41 8->41: 8->41 41->NULL: 41->NULL
广告