在 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

更新於: 17-4 月 2020

85 次瀏覽

開啟你的 職業生涯

透過完成課程獲取認證

開始
廣告
© . All rights reserved.