Skip to content
Related Articles

Related Articles

Next greater element in the Linked List
  • Difficulty Level : Medium
  • Last Updated : 08 Dec, 2020

Given a linked list L of integers, the task is to return a linked list of integers such that it contains next greater element for each element in the given linked list. If there doesn’t any greater element for any element then insert 0 for it.

Examples: 

Input: 2->1->3->0->5 
Output: 3->3->5->5->0

Input: 1->2->3 
Output: 2->3->0 

Naive Approach: The naive approach is traverse the linked list L, and for each element in the linked list find the next greater element in the list by traversing the whole string from the current element.



Time Complexity: O(N2)

Efficient Approach: The above naive approach can be optimized by maintaining a monotonically decreasing stack of elements traversed. If a greater element is found append it to the resultant linked list L’ else append 0. Below are the steps: 

  1. Push the first node to stack.
  2. Pick the rest of the node one by one and follow the following steps in the loop: 
    • Mark the current node as next node.
    • If the stack is not empty, compare the top node value of the stack with next node value.
    • If next node value is greater than the top node value then, Pop the top node from the stack and next is the next greater element for the popped node.
    • Keep popping the node from the stack while the popped node value is smaller than next node value. next node will becomes the next greater element for all such popped node.
  3. Finally, push the next node in the stack.
  4. After the loop in step 2 is over, pop all the node from the stack and print 0 as the next element for them.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// List Node
struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x)
    {
        val = x;
        next = NULL;
    }
};
 
// Function to reverse the LL
void rev(ListNode** head)
{
    ListNode *pre, *curr, *nex;
 
    pre = NULL;
    curr = *head;
    nex = curr->next;
 
    // Till current is not NULL
    while (curr) {
        curr->next = pre;
        pre = curr;
        curr = nex;
        nex = (curr)
                  ? curr->next
                  : NULL;
    }
    *head = pre;
}
 
// Function to print a LL node
void printList(ListNode* head)
{
    while (head) {
 
        cout << head->val
             << ' ';
        head = head->next;
    }
}
 
// Function to find the next greater
// element in the list
ListNode* nextLargerLL(ListNode* head)
{
    if (head == NULL)
        return NULL;
 
    // Dummy Node
    ListNode* res
        = new ListNode(-1);
    ListNode* temp = res;
 
    // Reverse the LL
    rev(&head);
    stack<int> st;
 
    while (head) {
 
        // Initial Condition
        if (st.empty()) {
            temp->next
                = new ListNode(0);
            st.push(head->val);
        }
        else {
 
            // Maintain Monotonicity
            // Decreasing stack of element
            while (!st.empty()
                   && st.top()
                          <= head->val)
                st.pop();
 
            // Update result LL
            if (st.empty()) {
                temp->next
                    = new ListNode(0);
 
                st.push(head->val);
            }
            else {
                temp->next
                    = new ListNode(st.top());
                st.push(head->val);
            }
        }
        head = head->next;
        temp = temp->next;
    }
 
    // Delete Dummy Node
    temp = res;
    res = res->next;
    delete temp;
 
    // Reverse result LL
    rev(&res);
    return res;
}
 
// Driver Code
int main()
{
    // Given Linked List
    ListNode* head = new ListNode(2);
    ListNode* curr = head;
 
    curr->next = new ListNode(1);
    curr = curr->next;
 
    curr->next = new ListNode(3);
    curr = curr->next;
 
    curr->next = new ListNode(0);
    curr = curr->next;
 
    curr->next = new ListNode(5);
    curr = curr->next;
 
    // Function Call
    printList(nextLargerLL(head));
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
public class linkedList
{
    ListNode head = null;
 
    // ListNode
    class ListNode
    {
        int val;
        ListNode next;
 
        public ListNode(int val)
        {
            this.val = val;
            next = null;
        }
    }
 
    // Function to reverse the Linked List
    ListNode reverse(ListNode head)
    {
        ListNode prev = null, next = null,
                               curr = head;
 
        while (curr != null)
        {
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
 
    // Function to find the next greater
    // element in the list
    ListNode nextLargerLL(ListNode head)
    {
        if (head == null)
            return head;
 
        // Dummy Node
        ListNode res = new ListNode(-1);
        ListNode temp = res;
 
        // Reverse the Linked List
        head = reverse(head);
        Stack<Integer> st = new Stack<>();
 
        while (head != null)
        {
 
            // Initial Condition
            if (st.empty())
            {
                temp.next = new ListNode(0);
                st.push(head.val);
            }
            else {
 
                // Maintain Monotonicity
                // Decreasing stack of element
                while (!st.empty() &&
                           st.peek() <= head.val)
                    st.pop();
 
                // Update result Linked List
                if (st.empty())
                {
                    temp.next = new ListNode(0);
                    st.push(head.val);
                }
                else
                {
                    temp.next = new ListNode(st.peek());
                    st.push(head.val);
                }
            }
            head = head.next;
            temp = temp.next;
        }
        temp = res;
        res = res.next;
 
        // Reverse result Linked List
        res = reverse(res);
 
        return res;
    }
 
    public void push(int new_data)
    {
        /* allocate node */
        ListNode new_node = new ListNode(new_data);
 
        /* link the old list off the new node */
        new_node.next = head;
 
        /* move the head to point to the new node */
        head = new_node;
    }
 
    // Utility function to print the linked list
    public void printList(ListNode head)
    {
        ListNode temp = head;
        while (temp != null)
        {
            System.out.print(temp.val + " ");
            temp = temp.next;
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        linkedList ll = new linkedList();
 
        ll.push(5);
        ll.push(0);
        ll.push(3);
        ll.push(1);
        ll.push(2);
 
        // Function Call
        ll.printList(ll.nextLargerLL(ll.head));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# List Node
class ListNode:
 
    def __init__(self, x):
 
        self.val = x
        self.next = None
  
# Function to reverse the LL
def rev(head):
  
    pre = None;
    curr = head;
    nex = curr.next;
  
    # Till current is not None
    while (curr):
        curr.next = pre;
        pre = curr;
        curr = nex;
        nex = (curr.next) if curr else None
     
    head = pre
    return head
  
# Function to print a LL node
def printList(head):
 
    while(head):
        print(str(head.val), end = ' ')
        head = head.next;
      
# Function to find the next greater
# element in the list
def nextLargerLL(head):
 
    if (head == None):
        return None;
  
    # Dummy Node
    res = ListNode(-1);
    temp = res;
  
    # Reverse the LL
    head = rev(head);
    st = []
  
    while (head):
  
        # Initial Condition
        if (len(st) == 0):
            temp.next = ListNode(0);
            st.append(head.val);
         
        else:
  
            # Maintain Monotonicity
            # Decreasing stack of element
            while (len(st) != 0 and st[-1]<= head.val):
                st.pop();
  
            # Update result LL
            if (len(st) == 0):
                temp.next = ListNode(0);
                st.append(head.val);
             
            else:
                temp.next = ListNode(st[-1]);
                st.append(head.val);
             
        head = head.next;
        temp = temp.next;
  
    # Delete Dummy Node
    temp = res;
    res = res.next;
    del temp;
  
    # Reverse result LL
    res = rev(res);
    return res;
  
# Driver Code
if __name__=='__main__':
     
    # Given Linked List
    head = ListNode(2);
    curr = head;
  
    curr.next = ListNode(1);
    curr = curr.next;
  
    curr.next = ListNode(3);
    curr = curr.next;
  
    curr.next = ListNode(0);
    curr = curr.next;
  
    curr.next = ListNode(5);
    curr = curr.next;
  
    # Function Call
    printList(nextLargerLL(head));
 
# This code is contributed by rutvik_56

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class linkedList{
     
ListNode head = null;
 
// ListNode
public class ListNode
{
    public int val;
    public ListNode next;
 
    public ListNode(int val)
    {
        this.val = val;
        next = null;
    }
}
 
// Function to reverse the Linked List
ListNode reverse(ListNode head)
{
    ListNode prev = null, next = null,
                          curr = head;
 
    while (curr != null)
    {
        next = curr.next;
        curr.next = prev;
        prev = curr;
        curr = next;
    }
    return prev;
}
 
// Function to find the next greater
// element in the list
ListNode nextLargerLL(ListNode head)
{
    if (head == null)
        return head;
 
    // Dummy Node
    ListNode res = new ListNode(-1);
    ListNode temp = res;
 
    // Reverse the Linked List
    head = reverse(head);
    Stack<int> st = new Stack<int>();
 
    while (head != null)
    {
         
        // Initial Condition
        if (st.Count == 0)
        {
            temp.next = new ListNode(0);
            st.Push(head.val);
        }
        else
        {
             
            // Maintain Monotonicity
            // Decreasing stack of element
            while (st.Count != 0 &&
                   st.Peek() <= head.val)
                st.Pop();
 
            // Update result Linked List
            if (st.Count == 0)
            {
                temp.next = new ListNode(0);
                st.Push(head.val);
            }
            else
            {
                temp.next = new ListNode(st.Peek());
                st.Push(head.val);
            }
        }
        head = head.next;
        temp = temp.next;
    }
    temp = res;
    res = res.next;
 
    // Reverse result Linked List
    res = reverse(res);
 
    return res;
}
 
public void Push(int new_data)
{
     
    // Allocate node
    ListNode new_node = new ListNode(new_data);
 
    // Link the old list off the new node
    new_node.next = head;
 
    // Move the head to point to the new node
    head = new_node;
}
 
// Utility function to print the linked list
public void printList(ListNode head)
{
    ListNode temp = head;
     
    while (temp != null)
    {
        Console.Write(temp.val + " ");
        temp = temp.next;
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    linkedList ll = new linkedList();
 
    ll.Push(5);
    ll.Push(0);
    ll.Push(3);
    ll.Push(1);
    ll.Push(2);
 
    // Function Call
    ll.printList(ll.nextLargerLL(ll.head));
}
}
 
// This code is contributed by Amit Katiyar

chevron_right


Output: 

3 3 5 5 0

 

Time Complexity: O(N) 
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :