1019. Next Greater Node In Linked List

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
private static class ListNodeWrapper {
private final int value;
private int nextLargerValue;

public ListNodeWrapper(int value) {
this.value = value;
}
}

public int[] nextLargerNodes(ListNode head) {
List<ListNodeWrapper> nodeList = new ArrayList<>();
Stack<Integer> decreaseStack = new Stack<>(); // 非严格单调递减栈,栈中存储的为节点的索引

ListNode curr = head;
int index = 0;
while (curr != null) {
while (!decreaseStack.isEmpty() && curr.val > nodeList.get(decreaseStack.peek()).value) {
// 出现了下一个更大的值
ListNodeWrapper node = nodeList.get(decreaseStack.pop());
node.nextLargerValue = curr.val;
}

nodeList.add(new ListNodeWrapper(curr.val));
decreaseStack.push(index);
index++;
curr = curr.next;
}

int[] answers = new int[nodeList.size()];
for (int i = 0; i < answers.length; i++) {
answers[i] = nodeList.get(i).nextLargerValue;
}
return answers;
}
}

References

1019. Next Greater Node In Linked List