题目
题目链接
题解
class Solution {
public int[] nextLargerNodes(ListNode head) {
if (head == null) {
return new int[0];
}
List<Integer> res = new ArrayList<>();
// 数组第一位存储下标,数组第二位存储值
Deque<int[]> stack = new ArrayDeque<>();
// 遍历数组
int index = 0;
ListNode node = head;
while (node != null) {
// 弹栈:栈非空 && 栈顶元素 > 当前节点
while (!stack.isEmpty() && node.val > stack.peek()[1]) {
int topIndex = stack.pop()[0];
res.set(topIndex, node.val);
}
// 压栈
int[] forPush = new int[2];
forPush[0] = index;
forPush[1] = node.val;
stack.push(forPush);
res.add(0);
// 指针后移
node = node.next;
index++;
}
// list转数组
int[] ans = new int[res.size()];
for (int i = 0; i < res.size(); i++) {
ans[i] = res.get(i);
}
return ans;
}
}