-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMin_Stack.cpp
More file actions
41 lines (34 loc) · 829 Bytes
/
Min_Stack.cpp
File metadata and controls
41 lines (34 loc) · 829 Bytes
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
/*
Min Stack Total
Design a stack that supports push, pop, top, and retrieving the minimum
element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
*/
class MinStack {
private:
stack<int> stack_;
stack<int> min_stack_;
public:
void push(int x) {
if (stack_.empty() || x <= min_stack_.top()) {
min_stack_.push(x);
}
stack_.push(x);
}
void pop() {
if (stack_.empty()) return;
if (stack_.top() == min_stack_.top()) {
min_stack_.pop();
}
stack_.pop();
}
int top() {
return stack_.top();
}
int getMin() {
return min_stack_.top();
}
};