在 C++ 中查詢單鏈表中最小的和最大的元素


在這個問題中,我們給定一個單鏈表。我們的任務是找到單鏈表中最小的和最大的元素。

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

輸入

linked List : 5 -> 2 -> 7 -> 3 ->9 -> 1 -> 4

輸出

Smallest element = 1
Largest element = 9

解決方案方法

解決這個問題的一個簡單方法是逐個遍歷連結串列節點。在此之前,我們將 maxElement 和 minElement 初始化為第一個元素的值,即 head -> data。然後,我們將逐個元素遍歷連結串列。然後將當前節點的值與 maxElement 進行比較,並將較大的值儲存在 maxElement 變數中。對 minElement 執行相同的操作以儲存較小的值。當遍歷完成時,列印兩個值。

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

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   struct Node* next;
};
void printLargestSmallestLinkedList(struct Node* head) {
   int maxElement = INT_MIN;
   int minElement = INT_MAX;
   while (head != NULL) {
      if (minElement > head->data)
         minElement = head->data;
      if (maxElement < head->data)
         maxElement = head->data;
      head = head->next;
   }
   cout<<"Smallest element in the linked list is : "<<minElement<<endl;
   cout<<"Largest element in the linked list is : "<<maxElement<<endl;
}
void push(struct Node** head, int data) {
   struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
   newNode->data = data;
   newNode->next = (*head);
   (*head) = newNode;
}
int main() {
   struct Node* head = NULL;
   push(&head, 5);
   push(&head, 2);
   push(&head, 7);
   push(&head, 3);
   push(&head, 9);
   push(&head, 1);
   push(&head, 4);
   printLargestSmallestLinkedList(head);
   return 0;
}

輸出

Smallest element in the linked list is : 1
Largest element in the linked list is : 9

更新時間: 16-Mar-2021

741 次瀏覽

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.