每日一题:链表中的下一个更大节点
题目链接:https://leetcode.cn/problems/next-greater-node-in-linked-list/
# 解题思路
维持一个非递增的单调栈即可
# 提交结果
# 代码
/** | |
* 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; | |
} | |
} |