forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Max_Stack.cpp
63 lines (56 loc) · 1.37 KB
/
Max_Stack.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
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
class MaxStack {
stack<int> stack1;
stack<int> stack2;
public:
/** initialize your data structure here. */
MaxStack() {
stack1 = stack<int> ();
stack2 = stack<int> ();
}
void push(int x) {
stack1.push(x);
if (stack2.empty() or x >= stack2.top()) {
stack2.push(x);
}
}
int pop() {
int element = stack1.top();
stack1.pop();
if (!stack2.empty() and stack2.top() == element) {
stack2.pop();
}
return element;
}
int top() {
return stack1.top();
}
int peekMax() {
return stack2.top();
}
int popMax() {
int maxElement = stack2.top();
stack<int> tmpStack;
while(!stack1.empty() and stack1.top() != maxElement) {
int element = stack1.top();
tmpStack.push(element);
stack1.pop();
}
stack1.pop();
stack2.pop();
while(!tmpStack.empty()) {
int x = tmpStack.top();
push(x);
tmpStack.pop();
}
return maxElement;
}
};
/**
* Your MaxStack object will be instantiated and called as such:
* MaxStack obj = new MaxStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.peekMax();
* int param_5 = obj.popMax();
*/