---
# System prepended metadata

title: Leetcode 1019. Next Greater Node In Linked List
tags: [Leetcode]

---

---
###### tags: `Leetcode`
---
# Leetcode 1019. Next Greater Node In Linked List


[link](https://leetcode.com/problems/next-greater-node-in-linked-list/)

---

You are given the head of a linked list with n nodes.

For each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it.

Return an integer array answer where answer[i] is the value of the next greater node of the ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0.

#### Example 1:

Input: head = [2,1,5]
Output: [5,5,0]

#### Example 2:

Input: head = [2,7,4,3,5]
Output: [7,0,5,5,0]



#### Constraints:

- The number of nodes in the list is n.
- 1 <= n <= 104
- 1 <= Node.val <= 109

---

Starts a while loop that continues as long as head is not None (i.e., there are still nodes left in the input list).

Starts an inner while loop that continues as long as stack is not empty and the value of the last element in stack (i.e., stack[-1][1]) is less than the value of the current node (head.val). This loop pops the last element off the stack, which represents a node whose next greater value is head.val, and updates the corresponding element in res to head.val.

Appends a new element to the end of stack that contains the index of the current node (len(res)) and the value of the current node (head.val).

Appends a 0 to the end of res, since we have not yet found the next greater value for the current node.

Moves head to the next node in the input list.

#### Solution 1
```python=
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:
        res, stack = [], []
        while head:
            while stack and stack[-1][1] < head.val:
                res[stack.pop()[0]] = head.val
            stack.append([len(res), head.val])
            res.append(0)
            head = head.next

        return res

        
```
O(T): O(N^2)
O(S): O(N)