In this article, we will discuss the solution for 1019th Problem from Leetcode – Next Greater Node In Linked List.

Let us see the question in brief before diving into the solution. Full question can be seen from this Leetcode link.

##### Problem

We are given a linked list with head as the first node. Let’s number the nodes in the list: node_1, node_2, node_3, … etc. Return an array of integers `answer`

, where `answer[i] = next_larger(node_{i+1})`

.

Example:

Input:[1,7,5,1,9,2,5,1]Output:[7,9,9,9,0,5,0,0]

So let us discuss the solution for the above problem.

##### Related Links

Linked List Series #1 – Introduction – Creating a Linked list

Linked List Insertion – Linked List Tutorial Series #2

Linked List Deletion – Linked List Tutorial Series #3

##### 1. Naive approach

In this very basic approach, for each node, we will traverse through remaining all elements to the right of that node and check which is bigger than this node. We will then add to list and return it.

As we can see, the time complexity of this approach will be O(N).

Is there any better way to do this?

##### 2. Using Stacks

In this approach, we will make use of stack. Here, each item of the stack is a tuple which consists of two values -> index, value.

We will also keep an answer list to be returned as solution. We will increment the index variable at each iteration.

If the stack is not empty and the stack’s top value is less than the current node value of linked list, we will pop the top item and insert it into answer as ans[index] = value.

If stack’s top value is greater than current node of linked list, we will add the index and value of linked list to the stack.

##### Solution

The solution in Python is as follows:

The code is commented wherever I find it necessary. Feel free to comment in case of any issues.

Do follow us for Coderefer newsletter to never miss an update from our Blog and YouTube channel. The video will be updated soon.