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:
n
.1 <= n <= 104
1 <= Node.val <= 109
Given the head of a linked list, find the value of the next greater node for each node. The next greater node for a given node is the first node to its right with a strictly larger value. If no such node exists, the next greater node is 0. Return an array where the i-th element is the value of the next greater node of the i-th node (1-indexed).
This problem can be efficiently solved using a monotonic stack. A monotonic stack is a stack where the elements are always in increasing or decreasing order. In this case, we'll use a decreasing monotonic stack.
Algorithm:
nums
.stk
and an array ans
of the same size as nums
, initialized with zeros. ans
will store the result.nums
from right to left (index i
from n-1
to 0, where n
is the length of nums
).nums[i]
:
stk[-1]
) is less than or equal to nums[i]
, pop elements from the stack. This ensures that the stack maintains a decreasing order.nums[i]
. Assign this value to ans[i]
.nums[i]
onto the stack.ans
contains the next greater node values for each node. Return ans
.nums
array and the stack. In the best-case scenario where the linked list is already in decreasing order, the stack space would be minimal.class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
nums = []
while head:
nums.append(head.val)
head = head.next
stk = []
n = len(nums)
ans = [0] * n
for i in range(n - 1, -1, -1):
while stk and stk[-1] <= nums[i]:
stk.pop()
if stk:
ans[i] = stk[-1]
stk.append(nums[i])
return ans
The code in other languages (Java, C++, Go, TypeScript, Rust, Javascript) follows a very similar structure, adapting the syntax and data structures to each language's specifics, but maintaining the same core algorithm. The fundamental idea of using a decreasing monotonic stack to efficiently find the next greater element remains consistent across all implementations.