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

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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;
};
int maxElement = INT_MIN;
int minElement = INT_MAX;
while (head != NULL) {
if (minElement > head->data)
if (maxElement < head->data)
}
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;
}
int main() {
struct Node* head = NULL;
}
Smallest element in the linked list is : 1
Largest element in the linked list is : 9