forked from lzl124631x/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
s1.cpp
29 lines (29 loc) · 801 Bytes
/
s1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// OJ: https://leetcode.com/problems/next-greater-node-in-linked-list/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
ListNode *reverseList(ListNode *head) {
ListNode h;
while (head) {
auto node = head;
head = head->next;
node->next = h.next;
h.next = node;
}
return h.next;
}
public:
vector<int> nextLargerNodes(ListNode* head) {
vector<int> ans;
stack<int> s;
head = reverseList(head);
for (; head; head = head->next) {
while (s.size() && s.top() <= head->val) s.pop();
ans.push_back(s.size() ? s.top() : 0);
s.push(head->val);
}
reverse(ans.begin(), ans.end());
return ans;
}
};