You are given the head
of a linked list with n
nodes.
For each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it.
Return an integer array answer
where answer[i]
is the value of the next greater node of the ith
node (1-indexed). If the ith
node does not have a next greater node, set answer[i] = 0
.
Example 1:
Input: head = [2,1,5] Output: [5,5,0]
Example 2:
Input: head = [2,7,4,3,5] Output: [7,0,5,5,0]
Constraints:
- The number of nodes in the list is
n
. 1 <= n <= 104
1 <= Node.val <= 109
题目链接:https://leetcode.com/problems/next-greater-node-in-linked-list/
题目大意:求链表每个值之后比它大的值
题目分析:单调栈模拟一下,需要记录进站的顺序
5ms,时间击败98.95%
/**
* 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 {
class Val {
int pos, val;
Val(int p, int v) {
this.pos = p;
this.val = v;
}
}
private int getLen(ListNode head) {
int ans = 0;
while(head != null) {
head = head.next;
ans++;
}
return ans;
}
public int[] nextLargerNodes(ListNode head) {
int n = getLen(head);
int[] ans = new int[n];
Val[] stk = new Val[n + 1];
int top = 0, i = 0;
stk[++top] = new Val(i, head.val);
while (head.next != null) {
i++;
int nxtVal = head.next.val;
if (nxtVal <= stk[top].val) {
stk[++top] = new Val(i, nxtVal);
} else {
while (top > 0 && stk[top].val < nxtVal) {
ans[stk[top].pos] = nxtVal;
top--;
}
stk[++top] = new Val(i, nxtVal);
}
head = head.next;
}
while (top > 0) {
ans[stk[top--].pos] = 0;
}
return ans;
}
}