Replace every node of a Linked list with the next greater element on right side

Given a linked list, the task is to find the Next Greater Element for every node of the linked list.
Note: For nodes with no next greater element, store -1 in the result.
Examples:
Input: linked list = [2, 1, 5]
Output: [5, 5, -1]Input: linked list = [2, 7, 4, 3, 5]
Output: [7, -1, 5, 5, -1]
Approach:
To solve the problem mentioned above the main idea is to use a Stack Data Structure.
- Iterate through the linked list and insert the value and position of elements of the linked list into a stack.
- Initialize the result vector with -1 for every node.
- Update the previous node’s value while the current node’s value is greater than the previous nodes and pop the value from the stack after updating.
Below is the implementation of the above approach:
C++
// C++ Program to find the// Next Greater Element for// a Linked List#include <bits/stdc++.h>using namespace std;// Linked List Nodestruct Node { int val; struct Node* next;};// Function to print// next greater elementvector<int> nextLargerNodes( struct Node* head){ int cur_pos = 0; stack<pair<int, int> > arr; vector<int> res; // Iterate for all // element in linked list while (head) { // Initialize every // position with 0 res.push_back(-1); // Check if current value is // greater then update previous while ( !arr.empty() && arr.top().second < head->val) { res[arr.top().first] = head->val; arr.pop(); } arr.push(make_pair( cur_pos, head->val)); cur_pos++; // Increment the head pointer head = head->next; } // Return the final result return res;}// Utility function to// create a new nodeNode* newNode(int val){ struct Node* temp = new Node; temp->val = val; temp->next = NULL; return temp;}// Driver Programint main(){ struct Node* head = newNode(2); head->next = newNode(7); head->next->next = newNode(4); head->next->next->next = newNode(3); head->next->next->next->next = newNode(5); vector<int> ans; ans = nextLargerNodes(head); for (int i = 0; i < ans.size(); i++) { cout << ans[i] << ", "; }} |
Java
// Java Program to find the// Next Greater Element for// a Linked Listimport java.util.*;class GFG{// Linked List Nodestatic class Node { int val; Node next;}; static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } ; // Function to print// next greater elementstatic Vector<Integer> nextLargerNodes(Node head){ int cur_pos = 0; Stack<pair > arr = new Stack<>(); Vector<Integer> res = new Vector<>(); // Iterate for all // element in linked list while (head != null) { // Initialize every // position with 0 res.add(-1); // Check if current value is // greater then update previous while (!arr.isEmpty() && arr.peek().second < head.val) { res.set(arr.peek().first, head.val); arr.pop(); } arr.add(new pair(cur_pos, head.val)); cur_pos++; // Increment the head // pointer head = head.next; } // Return the final result return res;}// Utility function to// create a new nodestatic Node newNode(int val){ Node temp = new Node(); temp.val = val; temp.next = null; return temp;}// Driver codepublic static void main(String[] args){ Node head = newNode(2); head.next = newNode(7); head.next.next = newNode(4); head.next.next.next = newNode(3); head.next.next.next.next = newNode(5); Vector<Integer> ans = new Vector<>(); ans = nextLargerNodes(head); for (int i = 0; i < ans.size(); i++) { System.out.print(ans.elementAt(i) + ", "); }}}// This code is contributed by Princi Singh |
Python3
# Python3 program to find the# Next Greater Element for# a Linked List# Linked List Nodeclass newNode: def __init__(self, val): self.val = val self.next = None# Function to print# next greater elementdef nextLargerNodes(head): cur_pos = 0 arr = [] res = [] # Iterate for all # element in linked list while (head): # Initialize every # position with 0 res.append(-1) # Check if current value is # greater then update previous while (len(arr) > 0 and arr[len(arr) - 1][1] < head.val): res[arr[len(arr) - 1][0]] = head.val arr.remove(arr[len(arr) - 1]) arr.append([cur_pos, head.val]) cur_pos += 1 # Increment the head pointer head = head.next # Return the final result return res# Driver codeif __name__ == '__main__': head = newNode(2) head.next = newNode(7) head.next.next = newNode(4) head.next.next.next = newNode(3) head.next.next.next.next = newNode(5) ans = nextLargerNodes(head) for i in range(len(ans)): print(ans[i], end = ", ")# This code is contributed by SURENDRA_GANGWAR |
C#
// C# Program to find the// Next Greater Element for// a Linked Listusing System;using System.Collections.Generic;class GFG{// Linked List Nodeclass Node { public int val; public Node next;}; class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } ; // Function to print// next greater elementstatic List<int> nextLargerNodes(Node head){ int cur_pos = 0; Stack<pair > arr = new Stack<pair>(); List<int> res = new List<int>(); // Iterate for all // element in linked list while (head != null) { // Initialize every // position with 0 res.Add(-1); // Check if current value is // greater then update previous while (arr.Count !=0 && arr.Peek().second < head.val) { res[arr.Peek().first] = head.val; arr.Pop(); } arr.Push(new pair(cur_pos, head.val)); cur_pos++; // Increment the head // pointer head = head.next; } // Return the readonly result return res;}// Utility function to// create a new nodestatic Node newNode(int val){ Node temp = new Node(); temp.val = val; temp.next = null; return temp;}// Driver codepublic static void Main(String[] args){ Node head = newNode(2); head.next = newNode(7); head.next.next = newNode(4); head.next.next.next = newNode(3); head.next.next.next.next = newNode(5); List<int> ans = new List<int>(); ans = nextLargerNodes(head); for (int i = 0; i < ans.Count; i++) { Console.Write(ans[i] + ", "); }}}// This code is contributed by shikhasingrajput |
Javascript
<script>// JavaScript program to find the// Next Greater Element for// a Linked List// Linked List Nodeclass newNode{ constructor(val){ this.val = val this.next = null }}// Function to print// next greater elementfunction nextLargerNodes(head){ let cur_pos = 0 let arr = [] let res = [] // Iterate for all // element in linked list while (head){ // Initialize every // position with 0 res.push(-1) // Check if current value is // greater then update previous while (arr.length> 0 && arr[arr.length- 1][1] < head.val){ res[arr[arr.length- 1][0]] = head.val arr.pop() } arr.push([cur_pos, head.val]) cur_pos += 1 // Increment the head pointer head = head.next } // Return the final result return res}// Driver codelet head = new newNode(2)head.next = new newNode(7)head.next.next = new newNode(4)head.next.next.next = new newNode(3)head.next.next.next.next = new newNode(5)ans = nextLargerNodes(head)for(let i=0;i<ans.length;i++) document.write(ans[i],", ")// This code is contributed by shinjanpatra</script> |
Output:
7, -1, 5, 5, -1,
Time Complexity: O(N)
Auxiliary Space Complexity: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



