Find smallest and largest elements in singly linked list in C++
C++Server Side ProgrammingProgramming
In this problem, we are given a singly linked list. Our task is to find the smallest and largest elements in single linked list.
Lets take an example to understand the problem,
Input
linked List : 5 -> 2 -> 7 -> 3 ->9 -> 1 -> 4Output
Smallest element = 1 Largest element = 9Solution Approach
A simple solution to the problem is using by traversing the linked list node by node. Prior to this, we will initialise maxElement and minElement to the value of the first element i.e. head -> data. Then we will traverse the linked list element by element. And then compare the value of the current node with maxElement and store the greater value in maxElement variable. Perform the same to store smaller values in minElement. When the traversal is done print both the values.
Program to illustrate the working of our solution,
Example
Live Demo
#include 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