Next Greater Element in a Circular Linked List | C ++ program for the above approach ; Node structure of the circular Linked list ; Constructor ; Function to print the elements of a Linked list ; Iterate the linked list ; Print the data ; Function to find the next greater element for each node ; Stores the head of circular Linked list ; Stores the head of the resulting linked list ; Stores the temporary head of the resulting Linked list ; Iterate until head is not equal to H ; Used to iterate over the circular Linked List ; Stores if there exist any next Greater element ; Iterate until head is not equal to curr ; If the current node is smaller ; Update the value of Val ; Update curr ; If res is Null ; Create new Node with value curr -> data ; Assign address of res to tempList ; Update tempList ; Assign address of the next node to tempList ; Update the value of head node ; Print the resulting Linked list ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; Node ( int d ) { data = d ; next = NULL ; } } ; void print ( Node * head ) { Node * temp = head ; while ( temp != NULL ) { cout << temp -> data << " ▁ " ; temp = temp -> next ; } } void NextGreaterElement ( Node * head ) { Node * H = head ; Node * res = NULL ; Node * tempList = NULL ; do { Node * curr = head ; int Val = -1 ; do { if ( head -> data < curr -> data ) { Val = curr -> data ; break ; } curr = curr -> next ; } while ( curr != head ) ; if ( res == NULL ) { res = new Node ( Val ) ; tempList = res ; } else { tempList -> next = new Node ( Val ) ; tempList = tempList -> next ; } head = head -> next ; } while ( head != H ) ; print ( res ) ; } int main ( ) { Node * head = new Node ( 1 ) ; head -> next = new Node ( 5 ) ; head -> next -> next = new Node ( 12 ) ; head -> next -> next -> next = new Node ( 10 ) ; head -> next -> next -> next -> next = new Node ( 0 ) ; head -> next -> next -> next -> next -> next = head ; NextGreaterElement ( head ) ; return 0 ; }