leetcode 1019. 链表中的下一个更大节点

题目描述

给出一个以头节点 head 作为第一个节点的链表。链表中的节点分别编号为:node_1, node_2, node_3, ...
每个节点都可能有下一个更大值(next larger value):对于 node_i,如果其 next_larger(node_i)node_j.val,那么就有j > inode_j.val > node_i.val,而j是可能的选项中最小的那个。如果不存在这样的j,那么下一个更大值为0
返回整数答案数组 answer,其中 answer[i] = next_larger(node_{i+1})
注意:在下面的示例中,诸如 [2,1,5] 这样的输入(不是输出)是链表的序列化表示,其头节点的值为 2,第二个节点值为 1,第三个节点值为 5 。
相关话题: 栈、链表    难度: 中等

示例 1:
输入:[2,1,5]
输出:[5,5,0]

示例 2:
输入:[2,7,4,3,5]
输出:[7,0,5,5,0]

示例 3:
输入:[1,7,5,1,9,2,5,1]
输出:[7,9,9,9,0,5,0,0]

提示:

  • 对于链表中的每个节点,1 <= node.val <= 10^9
  • 给定列表的长度在 [0, 10000] 范围内

思路:
使用单调栈结构,以[2,7,4,3,5]为例

  • 遍历链表,如果栈不为空,并且当前节点的值大于栈顶的值,那么进行结算,栈顶元素所代表的节点的下一个更大节点就是使它弹出的节点(遍历到的当前节点);否则,直接压入栈中
  • 遍历结束,如果栈不为空,则弹出所有元素,因为没有任何一个节点能令它们弹出,它们没有下一个更大节点


    17253929-ddb5cd2f89052f04.png
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

class Solution {
    static class Entry{
    public int index;
    public int val;
    public Entry(int index, int val){
        this.index = index;
        this.val = val;
    }
    }
    public int[] nextLargerNodes(ListNode head) {
        Stack<Entry> stack = new Stack<Entry>();
        int index = 0;
        int length = 0;
        for(ListNode p = head;p != null;p = p.next){
            length++;
        }
        int[] res = new int[length];
        for(ListNode p = head;p != null;p = p.next){
           //持续弹栈结算,知道栈顶元素大于当前节点或者栈为空
            while(!stack.isEmpty() && stack.peek().val < p.val){
                Entry x = stack.pop();
                res[x.index] = p.val;
            }
            stack.push(new Entry(index++, p.val));
        }
        while(!stack.isEmpty()){
            Entry x = stack.pop();
            res[x.index] = 0;
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_34005042/article/details/90912173
今日推荐