在 C++ 中找到雙鏈表中的最大節點


在此問題中,我們獲得了一個雙鏈表 LL。我們的任務是在雙鏈表中找到最大的節點

讓我們舉個例子來理解這個問題,

Input : linked-list = 5 -> 2 -> 9 -> 8 -> 1 -> 3
Output : 9

解決方案方法

解決此問題的一種簡單方法是遍歷連結串列,如果 max 的資料值大於 maxVal 的資料。遍歷連結串列後,我們將返回 macVal 節點的資料。

示例

演示我們解決方案工作原理的程式

#include <iostream>
using namespace std;
struct Node{
   int data;
   struct Node* next;
   struct Node* prev;
};
void push(struct Node** head_ref, int new_data){
   struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
   new_node->data = new_data;
   new_node->prev = NULL;
   new_node->next = (*head_ref);
   if ((*head_ref) != NULL)
      (*head_ref)->prev = new_node;
   (*head_ref) = new_node;
}
int findLargestNodeInDLL(struct Node** head_ref){
   struct Node *maxVal, *curr;
   maxVal = curr = *head_ref;
   while (curr != NULL){
      if (curr->data > maxVal->data)
         maxVal = curr;
      curr = curr->next;
   }
   return maxVal->data;
}
int main(){
   struct Node* head = NULL;
   push(&head, 5);
   push(&head, 2);
   push(&head, 9);
   push(&head, 1);
   push(&head, 3);
   cout<<"The largest node in doubly linked-list is "<<findLargestNodeInDLL(&head);
   return 0;
}

輸出

The largest node in doubly linked-list is 9

更新於:2022 年 1 月 28 日

270 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告