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.
publicint[]nextLargerNodes(ListNode head) {
List<Integer> vals =new ArrayList<>();
while (head !=null) { vals.add(head.val); head = head.next; }
int[] res =newint[vals.size()];
Stack<Integer> st =new Stack<>();
for (int i = 0; i < vals.size(); i++) {
while (!st.isEmpty() && vals.get(i) > vals.get(st.peek())) {
res[st.pop()]= vals.get(i);
}
st.push(i);
}
return res;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
funnextLargerNodes(head: ListNode?): IntArray {
val vals = mutableListOf<Int>()
var node = head
while (node !=null) {
vals.add(node.`val`)
node = node.next
}
val res = IntArray(vals.size)
val st = ArrayDeque<Int>()
for (i in vals.indices) {
while (st.isNotEmpty() && vals[i] > vals[st.last()]) {
res[st.removeLast()] = vals[i]
}
st.addLast(i)
}
return res
}
1
2
3
4
5
6
7
8
9
10
11
12
defnextLargerNodes(head):
vals = []
while head:
vals.append(head.val)
head = head.next
res = [0] * len(vals)
st = []
for i, v in enumerate(vals):
while st and v > vals[st[-1]]:
res[st.pop()] = v
st.append(i)
return res