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
维护一个单调递减的栈, 用来表示后面节点的最大值情况, 如果当前节点的值小于栈顶的值, 则 pop, 直到遇到比当前值大的值, 该值即当前值右侧第一个大于它的值。
impl Solution {
fn rc(head: Option<Box<ListNode>>, ans: &mut Vec<i32>) -> Vec<i32> {
if let Some(mut node) = head {
let mut l = Solution::rc(node.next.take(), ans);
while let Some(v) = l.pop() {
if v > node.val {
l.push(v);
break;
}
}
ans.push(if l.is_empty() { 0 } else { *l.last().unwrap() });
l.push(node.val);
return l;
}
Vec::new()
}
pub fn next_larger_nodes(head: Option<Box<ListNode>>) -> Vec<i32> {
let mut ans = Vec::new();
Solution::rc(head, &mut ans);
ans.reverse();
ans
}
}