Find smallest and largest elements in singly linked list in C++


In this problem, we are given a singly linked list. Our task is to find the smallest and largest elements in single linked list.

Let’s take an example to understand the problem,

Input

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

Output

Smallest element = 1
Largest element = 9

Solution 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 <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;
}

Output

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

Updated on: 16-Mar-2021

597 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements