G
N
I
D
A
O
L

每日一题:链表中的下一个更大节点

题目链接:https://leetcode.cn/problems/next-greater-node-in-linked-list/

# 解题思路

维持一个非递增的单调栈即可

# 提交结果

image.png

# 代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public int[] nextLargerNodes(ListNode head) {
        ListNode ass = head;
        List<Integer> list = new ArrayList<>();
        while (ass != null) {
            list.add(ass.val);
            ass = ass.next;
        }
        int n = list.size();
        int[] ret = new int[n];
        
        // 单调栈,非递增
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < n; ++i) {
            while (!stack.isEmpty() && list.get(stack.peek()) < list.get(i)) {
                // 出栈
                int j = stack.pop();
                ret[j] = list.get(i);
            }
            // 入栈
            stack.push(i);
        }
        return ret;
    }
}
更新于 阅读次数

😉觉得写的还不错,请我喝杯咖啡吧😁

独步凌波 微信支付

微信支付

独步凌波 支付宝

支付宝