-
Notifications
You must be signed in to change notification settings - Fork 0
/
MinStack.cpp
51 lines (46 loc) · 994 Bytes
/
MinStack.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
/*
*Min Stack
*Author: shuaijiang
*Email: zhaoshuaijiang8@gmail.com
*/
#include<iostream>
#include<vector>
#include<stdlib.h>
using namespace std;
class MinStack {
public:
vector<int> stack;
vector<int> minStack;
vector<int>::iterator iter, minIter;
vector<int>::reverse_iterator reiter;
void push(int x) {
stack.push_back(x);
if(minStack.size()<1)
minStack.push_back(x);
else{
reiter = minStack.rbegin();
if(x <= *reiter)
minStack.push_back(x);
}
}
void pop() {
if(stack.size() < 1)
return ;
reiter = stack.rbegin();
int num = * reiter;
reiter = minStack.rbegin();
int minNum = *reiter;
stack.pop_back();
if(num == minNum){
minStack.pop_back();
}
}
int top() {
reiter = stack.rbegin();
return *reiter;
}
int getMin() {
reiter = minStack.rbegin();
return *reiter;
}
};