題目
解答
class Solution {Stack<Integer> stack = new Stack<>();List<Integer> values = new LinkedList<>();public int[] nextLargerNodes(ListNode head) {nextLargerNodes2(head);return values.stream().mapToInt(x -> x).toArray();}public void nextLargerNodes2(ListNode head) {if (head == null) {return;}nextLargerNodes2(head.next);while (!stack.isEmpty() && stack.peek() <= head.val) {stack.pop();}int value = !stack.isEmpty() ? stack.peek() : 0;values.addFirst(value);stack.push(head.val);}
}
總結
通過遞歸,實現從最末尾的對象開始遍歷,當輸入的規模變大時,可能出現棧溢出的現象。