-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1019.cpp
More file actions
65 lines (63 loc) · 1.37 KB
/
1019.cpp
File metadata and controls
65 lines (63 loc) · 1.37 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#if 0
class Solution
{
public:
vector<int> nextLargerNodes(ListNode* head)
{
vector<int> res;
ListNode* cur = head;
while(cur != NULL)
{
ListNode* next = cur->next;
while(next != NULL)
{
if(next->val > cur->val) {
res.push_back(next->val);
break;
}
next = next->next;
}
if(next == nullptr)
res.push_back(0);
cur = cur->next;
}
return res;
}
};
#endif
class Solution
{
public:
vector<int> nextLargerNodes(ListNode* head)
{
stack<int> nodes;
stack<int> stk;
int length = 0;
while(head)
{
nodes.push(head->val);
head = head->next;
length++;
}
vector<int> result(length);
while(!nodes.empty())
{
int node = nodes.top();
nodes.pop();
while(!stk.empty() && node >= stk.top()) {
stk.pop();
}
result[--length] = stk.empty() ? 0 : stk.top();
stk.push(node);
}
return result;
}
};