Next greater element in the Linked List
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. As, we found next greater element for current head we add the next greater element to ans array and at last we return ans array.
C++
#include<bits/stdc++.h>
using namespace std;
struct Node
{
public :
int val;
Node* next;
Node( int data){
val = data;
next = NULL;
}
};
int sizeOfLL(Node* head)
{
int count = 0;
while (head != NULL)
{
count = count + 1;
head = head->next;
}
return count;
}
vector< int > nextLargerLL(Node* head)
{
int count = sizeOfLL(head);
vector< int > ans(count, 0);
int k = 0;
Node* j = NULL;
int temp = 0;
while (head != NULL){
if (head->next == NULL){
ans[k] = 0;
break ;
}
j = head->next;
if (head->val < j->val){
ans[k] = j->val;
k += 1;
}
else if (head->val >= j->val)
{
while (j != NULL && head->val >= j->val)
{
j = j->next;
}
if (j != NULL){
ans[k] = j->val;
k += 1;
}
else {
ans[k] = 0;
k += 1;
}
}
else {
ans[k] = 0;
k += 1;
}
head = head->next;
}
return ans;
}
Node* push(Node* head, int new_data)
{
Node* new_node = new Node(new_data);
new_node->next = head;
head = new_node;
return head;
}
void printList(vector< int > &ans){
cout << "[" ;
for ( int i = 0; i < ans.size(); i++){
if (i == ans.size() - 1) cout << ans[i];
else cout << ans[i] << ", " ;
}
cout << "]" ;
}
int main(){
Node* head = NULL;
head = push(head, 5);
head = push(head, 0);
head = push(head, 3);
head = push(head, 1);
head = push(head, 2);
vector< int > ans = nextLargerLL(head);
printList(ans);
return 0;
}
|
Java
import java.util.*;
public class linkedList {
ListNode head = null ;
class ListNode {
int val;
ListNode next;
public ListNode( int val)
{
this .val = val;
next = null ;
}
}
public int [] nextLargerLL(ListNode head)
{
int count = sizeOfLL(head);
int [] ans = new int [count];
int k = 0 ;
ListNode j;
int temp = 0 ;
while (head != null ) {
if (head.next == null ) {
ans[k] = 0 ;
break ;
}
j = head.next;
if (head.val < j.val) {
ans[k] = j.val;
k++;
}
else if (head.val
>= j.val) {
while (
j != null
&& head.val
>= j.val) {
j = j.next;
}
if (j != null ) {
ans[k] = j.val;
k++;
}
else {
ans[k] = 0 ;
k++;
}
}
else {
ans[k] = 0 ;
k++;
}
head = head.next;
}
return ans;
}
public void push( int new_data)
{
ListNode new_node = new ListNode(new_data);
new_node.next = head;
head = new_node;
}
public void printList()
{
System.out.println(Arrays.toString(nextLargerLL(head)));
}
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 );
ll.nextLargerLL(ll.head);
ll.printList();
}
public int sizeOfLL(ListNode head)
{
int count = 0 ;
while (head != null ) {
count = count + 1 ;
head = head.next;
}
return count;
}
}
|
Python3
head = None
class ListNode:
def __init__( self , val):
self .val = val
self . next = None
def sizeOfLL(head):
count = 0
while (head ! = None ):
count = count + 1
head = head. next
return count
def nextLargerLL(head):
count = sizeOfLL(head)
ans = [ None ] * count
k = 0
j = None
temp = 0
while (head ! = None ):
if (head. next = = None ):
ans[k] = 0
break
j = head. next
if (head.val < j.val):
ans[k] = j.val
k + = 1
elif (head.val > = j.val):
while (
j ! = None and head.val > = j.val):
j = j. next
if (j ! = None ):
ans[k] = j.val
k + = 1
else :
ans[k] = 0
k + = 1
else :
ans[k] = 0
k + = 1
head = head. next
return ans
def push(new_data):
global head
new_node = ListNode(new_data)
new_node. next = head
head = new_node
def printList():
print (nextLargerLL(head))
if __name__ = = '__main__' :
push( 5 )
push( 0 )
push( 3 )
push( 1 )
push( 2 )
nextLargerLL(head)
printList()
|
C#
using System;
using System.Collections.Generic;
public class linkedList {
ListNode head = null ;
class ListNode {
public int val;
public ListNode next;
public ListNode( int val)
{
this .val = val;
next = null ;
}
}
int [] nextLargerLL(ListNode head)
{
int count = sizeOfLL(head);
int [] ans = new int [count];
int k = 0;
ListNode j;
int temp = 0;
while (head != null ) {
if (head.next == null ) {
ans[k] = 0;
break ;
}
j = head.next;
if (head.val < j.val) {
ans[k] = j.val;
k++;
}
else if (head.val
>= j.val) {
while (
j != null
&& head.val
>= j.val) {
j = j.next;
}
if (j != null ) {
ans[k] = j.val;
k++;
}
else {
ans[k] = 0;
k++;
}
}
else {
ans[k] = 0;
k++;
}
head = head.next;
}
return ans;
}
public void push( int new_data)
{
ListNode new_node = new ListNode(new_data);
new_node.next = head;
head = new_node;
}
void printList()
{
foreach ( int a in nextLargerLL(head))
Console.Write(a+ " " );
}
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);
ll.nextLargerLL(ll.head);
ll.printList();
}
int sizeOfLL(ListNode head)
{
int count = 0;
while (head != null ) {
count = count + 1;
head = head.next;
}
return count;
}
}
|
Javascript
<script>
let head = null
class ListNode
{
constructor(val)
{
this .val = val
this .next = null
}
}
function sizeOfLL(head)
{
let count = 0
while (head != null )
{
count = count + 1
head = head.next
}
return count
}
function nextLargerLL(head)
{
let count = sizeOfLL(head)
let ans = new Array(count).fill( null )
let k = 0
let j = null
let temp = 0
while (head != null )
{
if (head.next == null ){
ans[k] = 0
break
}
j = head.next
if (head.val < j.val){
ans[k] = j.val
k += 1
}
else if (head.val >= j.val)
{
while (j != null && head.val >= j.val)
{
j = j.next
}
if (j != null ){
ans[k] = j.val
k += 1
}
else {
ans[k] = 0
k += 1
}
}
else {
ans[k] = 0
k += 1
}
head = head.next
}
return ans
}
function push(new_data)
{
let new_node = new ListNode(new_data)
new_node.next = head
head = new_node
}
function printList(){
document.write(nextLargerLL(head))
}
push(5)
push(0)
push(3)
push(1)
push(2)
nextLargerLL(head)
printList()
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(1)
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:
- Push the first node to stack.
- 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.
- Finally, push the next node in the stack.
- 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++
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode( int x)
{
val = x;
next = NULL;
}
};
void rev(ListNode** head)
{
ListNode *pre, *curr, *nex;
pre = NULL;
curr = *head;
nex = curr->next;
while (curr) {
curr->next = pre;
pre = curr;
curr = nex;
nex = (curr)
? curr->next
: NULL;
}
*head = pre;
}
void printList(ListNode* head)
{
while (head) {
cout << head->val
<< ' ' ;
head = head->next;
}
}
ListNode* nextLargerLL(ListNode* head)
{
if (head == NULL)
return NULL;
ListNode* res
= new ListNode(-1);
ListNode* temp = res;
rev(&head);
stack< int > st;
while (head) {
if (st.empty()) {
temp->next
= new ListNode(0);
st.push(head->val);
}
else {
while (!st.empty()
&& st.top()
<= head->val)
st.pop();
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;
}
temp = res;
res = res->next;
delete temp;
rev(&res);
return res;
}
int main()
{
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;
printList(nextLargerLL(head));
return 0;
}
|
Java
import java.util.*;
public class linkedList
{
ListNode head = null ;
class ListNode
{
int val;
ListNode next;
public ListNode( int val)
{
this .val = val;
next = null ;
}
}
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;
}
ListNode nextLargerLL(ListNode head)
{
if (head == null )
return head;
ListNode res = new ListNode(- 1 );
ListNode temp = res;
head = reverse(head);
Stack<Integer> st = new Stack<>();
while (head != null )
{
if (st.empty())
{
temp.next = new ListNode( 0 );
st.push(head.val);
}
else {
while (!st.empty() &&
st.peek() <= head.val)
st.pop();
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;
res = reverse(res);
return res;
}
public void push( int new_data)
{
ListNode new_node = new ListNode(new_data);
new_node.next = head;
head = new_node;
}
public void printList(ListNode head)
{
ListNode temp = head;
while (temp != null )
{
System.out.print(temp.val + " " );
temp = temp.next;
}
}
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 );
ll.printList(ll.nextLargerLL(ll.head));
}
}
|
Python3
class ListNode:
def __init__( self , x):
self .val = x
self . next = None
def rev(head):
pre = None ;
curr = head;
nex = curr. next ;
while (curr):
curr. next = pre;
pre = curr;
curr = nex;
nex = (curr. next ) if curr else None
head = pre
return head
def printList(head):
while (head):
print ( str (head.val), end = ' ' )
head = head. next ;
def nextLargerLL(head):
if (head = = None ):
return None ;
res = ListNode( - 1 );
temp = res;
head = rev(head);
st = []
while (head):
if ( len (st) = = 0 ):
temp. next = ListNode( 0 );
st.append(head.val);
else :
while ( len (st) ! = 0 and st[ - 1 ]< = head.val):
st.pop();
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 ;
temp = res;
res = res. next ;
del temp;
res = rev(res);
return res;
if __name__ = = '__main__' :
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 ;
printList(nextLargerLL(head));
|
C#
using System;
using System.Collections.Generic;
class linkedList{
ListNode head = null ;
public class ListNode
{
public int val;
public ListNode next;
public ListNode( int val)
{
this .val = val;
next = null ;
}
}
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;
}
ListNode nextLargerLL(ListNode head)
{
if (head == null )
return head;
ListNode res = new ListNode(-1);
ListNode temp = res;
head = reverse(head);
Stack< int > st = new Stack< int >();
while (head != null )
{
if (st.Count == 0)
{
temp.next = new ListNode(0);
st.Push(head.val);
}
else
{
while (st.Count != 0 &&
st.Peek() <= head.val)
st.Pop();
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;
res = reverse(res);
return res;
}
public void Push( int new_data)
{
ListNode new_node = new ListNode(new_data);
new_node.next = head;
head = new_node;
}
public void printList(ListNode head)
{
ListNode temp = head;
while (temp != null )
{
Console.Write(temp.val + " " );
temp = temp.next;
}
}
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);
ll.printList(ll.nextLargerLL(ll.head));
}
}
|
Javascript
<script>
class ListNode {
constructor(x)
{
this .val = x;
this .next = null ;
}
};
function rev(head)
{
var pre, curr, nex;
pre = null ;
curr = head;
nex = curr.next;
while (curr) {
curr.next = pre;
pre = curr;
curr = nex;
nex = (curr)
? curr.next
: null ;
}
head = pre;
return head;
}
function printList( head)
{
while (head) {
document.write( head.val
+ ' ' );
head = head.next;
}
}
function nextLargerLL(head)
{
if (head == null )
return null ;
var res
= new ListNode(-1);
var temp = res;
head = rev(head);
var st = [];
while (head) {
if (st.length==0) {
temp.next
= new ListNode(0);
st.push(head.val);
}
else {
while (st.length != 0
&& st[st.length - 1]
<= head.val)
st.pop();
if (st.length == 0) {
temp.next
= new ListNode(0);
st.push(head.val);
}
else {
temp.next
= new ListNode(st[st.length - 1]);
st.push(head.val);
}
}
head = head.next;
temp = temp.next;
}
temp = res;
res = res.next;
delete temp;
res = rev(res);
return res;
}
var head = new ListNode(2);
var 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;
printList(nextLargerLL(head));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
07 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...