Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ค้นหาองค์ประกอบที่เล็กที่สุดและใหญ่ที่สุดในรายการลิงก์เดียวใน C++


ในปัญหานี้ เราได้รับรายการที่เชื่อมโยงเพียงอย่างเดียว งานของเราคือค้นหาองค์ประกอบที่เล็กที่สุดและใหญ่ที่สุดในรายการที่เชื่อมโยงเดียว

มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน

อินพุต

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

ผลลัพธ์

Smallest element = 1
Largest element = 9

แนวทางการแก้ปัญหา

วิธีแก้ปัญหาอย่างง่ายคือใช้โดยข้ามผ่านโหนดรายการที่ถูกเชื่อมโยงโดยโหนด ก่อนหน้านี้ เราจะเริ่มต้น maxElement และ minElement เป็นค่าขององค์ประกอบแรกเช่น head -> data จากนั้นเราจะสำรวจองค์ประกอบ linkedlist ตามองค์ประกอบ จากนั้นเปรียบเทียบค่าของโหนดปัจจุบันกับ 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