ในปัญหานี้ เราได้รับ singly linked list งานของเราคือหาค่าน้อยที่สุดและมากที่สุดใน singly linked list
มาดูตัวอย่างเพื่อเข้าใจปัญหา
Input
linked List: 5 -> 2 -> 7 -> 3 -> 9 -> 1 -> 4
Output
Smallest element = 1 Largest element = 9
วิธีแก้ปัญหา
วิธีแก้ที่ง่ายคือการทะลุ linked list โหนดต่อโหนด ก่อนหน้านั้น เราจะกำหนดค่าเริ่มต้น maxElement และ minElement เป็นค่าขององค์ประกอบแรก คือ head -> data จากนั้นเราจะทะลุ linked list องค์ประกอบต่อองค์ประกอบ และเปรียบเทียบค่าของโหนดปัจจุบันกับ 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