LeetCode solutions

1072. Next Greater Node In Linked List

My accepted Python solution to LeetCode problem 1072, Next Greater Node In Linked List, running in 17ms.

  • Difficulty: Medium
  • Python
  • Runtime 17ms
  • Memory 21.4MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 17ms, memory 21.4MB, accepted 2026-01-02.

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]:
        # Convert to array first
        values = []
        while head:
            values.append(head.val)
            head = head.next
        
        n = len(values)
        result = [0] * n
        stack = []  # stack of indices
        
        for i in range(n):
            while stack and values[stack[-1]] < values[i]:
                idx = stack.pop()
                result[idx] = values[i]
            stack.append(i)
        
        return result

Source