Find minimum and maximum elements in singly Circular Linked List in C++


Here we will see how to get the minimum and maximum value from one singly circular linked linear list. The basic concept is very simple. The next part of the last node will be pointed to the first node, the first node will also be pointed using start pointer. When we insert some element into the list, after inserting the next part of the newly inserted node will be updated with the address of the start node.

Initially the min is assigned with positive infinity, and max is assigned with negative infinity. Now traverse the list from left to right. If the current element is less than the min element, then update min, if the current element is larger than the max element, then update the max. Thus we can get the min and max values.

Example

#include<iostream>
using namespace std;
class Node{
   public:
   int data;
   Node *next;
};
Node* getNode(int key){
   Node *newNode = new Node();
   newNode->data = key;
   newNode->next = NULL;
   return newNode;
}
void insert(Node **start, int data){
   Node *current = *start;
   Node *newNode = getNode(data);
   if(*start == NULL){
      newNode->next = newNode;
      *start = newNode;
      return;
   }
   while (current->next != *start) {
      current = current->next;
   }
   newNode->next = *start;
   current->next = newNode;
}
void displayList(Node *start){
   Node* current = start;
   if (start == NULL) {
      cout << "Display List is empty";
      return;
   } else {
      do {
         cout << current->data << " ";
         current = current->next;
      }
       while (current != start);
   }
   cout << endl;
}
void getMinMax(Node **start){
   if(*start == NULL){
      return;
   }
   Node* current;
   current = *start;
   int min = INT_MAX, max = INT_MIN;
   while (current->next != *start) {
      if (current->data < min) {
         min = current->data;
      }
      if (current->data > max) {
         max = current->data;
      }
      current = current->next;
   }
   cout << "Minimum: " << min << ", Maximum: " << max;
}
int main() {
   int data[] = {99, 11, 22, 10, 44, 55, 66};
   int n = sizeof(data)/sizeof(data[0]);
   Node *start = NULL;
   for(int i = 0; i<n; i++){
      insert(&start, data[i]);
   }
   displayList(start);
   getMinMax(&start);
}

Output

99 11 22 10 44 55 66
Minimum: 10, Maximum: 99

Updated on: 22-Oct-2019

299 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements