इस समस्या में, हमें एक सिंगली लिंक्ड लिस्ट दी गई है। हमारा कार्य सिंगल लिंक्ड लिस्ट में सबसे छोटा और सबसे बड़ा तत्व खोजना है।
आइए एक उदाहरण से इस समस्या को समझते हैं,
इनपुट
लिंक्ड लिस्ट: 5 -> 2 -> 7 -> 3 -> 9 -> 1 -> 4
आउटपुट
सबसे छोटा तत्व = 1 सबसे बड़ा तत्व = 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