单调栈系列~LeetCode1019.链表的下一个更大的节点(中等)


思路:

  1. 将链表转换成列表存储,因为列表的查询速度快。
  2. 如果当前元素比栈顶元素的值还要大,并且栈不为空,那么一直弹栈,弹出来的元素对应的更大的数就是当前要进栈的数。
  3. 如果不满足上述条件就将当前元素的下标进栈。
  4. 如果所有元素都遍历结束,栈中还有元素,那么说明栈中的元素后面没有比他自己更大的元素。
/** * 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;
    }
}
全部评论

相关推荐

头发暂时没有的KFC总裁:找廉价劳动力罢了
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务