https://leetcode.com/problems/next-greater-node-in-linked-list/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
vector<int> nextLargerNodes(ListNode* head) {
vector<int> res;
ListNode* cur=head;
while(cur!=NULL){
res.push_back(cur->val);
cur=cur->next;
}
int n=res.size();
stack<int>St;
vector<int>ans(n);
for(int i=0;i<n;i++){
while(!St.empty()&&res[i]>res[St.top()]){
ans[St.top()]=res[i];
St.pop();
}
St.push(i);
}
while (!St.empty()) {
ans[St.top()]=0;
St.pop();
}
return ans;
}
};
//护一个单调递减的栈,如果当前元素比栈顶元素大,则持续出栈直到不满足这个条件。这些出栈的元素的答案就是当前元素,然后当前元素进栈。
//最后还在栈中的元素的答案就是 0。