Next Greater Element in a Circular Linked List
Input: head = 1 → 5 → 2 → 10 → 0 → (head)
Output: 5 10 10 -1 1
The next greater elements of each node are:
- Node 1: Next greater element is 5.
- Node 5: Next greater element is 10.
- Node 2: Next greater element is 10.
- Node 10: No next greater element exists. Therefore print “-1”.
- Node 0: No next greater element exists. Therefore print “-1”.
Input: head = 1 → 5 → 12 → 10 → 0 → (head)
Output: 5 12 -1 12 1
Approach: The given problem can be solved by iterating the circular linked list to the right until the same element appears again and then print the next greater element found for each node. Follow the steps below to solve the problem:
- Initialize a Node variable, say res as NULL to store the head node of the Linked List representing the next greater element.
- Also, initialize a Node variable, say tempList as NULL to iterate over the Linked List representing the next greater element.
- Iterate over the circular Linked List and perform the following steps:
- Initialize a Node, say curr to store the reference to the current node of the circular linked list.
- Initialize a variable say Val as -1 to store the value of the next greater element of the current node.
- Perform the following steps until curr is not equal to the reference of the current node of the circular Linked List:
- If the value at the current node curr is greater than the value of the current node of the circular Linked list then assign the value of curr.data to Val and break out of the loop.
- Update the value of curr node as curr = curr.next.
- If the node res is NULL then create a new node with value Val and assign it to res, and then assign the value of res to tempList.
- Otherwise, create a new node with value Val and assign it to tempList.next, and then update the node tempList as tempList = tempList.next.
- After completing the above steps, print the elements of the Linked List res as the answer.
Below is the implementation of the above approach:
5 12 -1 12 1
Time Complexity: O(N2)
Auxiliary Space: O(N)