单调栈系列~LeetCode1019.链表的下一个更大的节点(中等)
思路:
- 将链表转换成列表存储,因为列表的查询速度快。
- 如果当前元素比栈顶元素的值还要大,并且栈不为空,那么一直弹栈,弹出来的元素对应的更大的数就是当前要进栈的数。
- 如果不满足上述条件就将当前元素的下标进栈。
- 如果所有元素都遍历结束,栈中还有元素,那么说明栈中的元素后面没有比他自己更大的元素。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
public int[] nextLargerNodes(ListNode head) {
Stack<Integer> stack = new Stack<>();
List<Integer> list = new ArrayList<>();
ListNode p = head;
while(p != null){
list.add(p.val);
p = p.next;
}
int []res = new int[list.size()];
for(int i=0; i<list.size(); i++){
while(!stack.isEmpty() && list.get(stack.peek()) < list.get(i)){
res[stack.pop()] = list.get(i);
}
stack.push(i);
}
while(!stack.isEmpty()){
res[stack.pop()] = 0;
}
return res;
}
}