forked from taohi/interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path21-minStack.cpp
68 lines (62 loc) · 1.18 KB
/
21-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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <stack>
using namespace::std;
class minStack
{
private:
stack <int> datastack;
stack <int> minstack;
public:
int top();
void pop();
void push(int);
void getMin();
};
int minStack::top()
{
return datastack.top();
}
void minStack::pop()
{
cout<<"pop():\t\t";
if(datastack.empty()||minstack.empty())
cout << "stack empty."<<endl;
else
{
if(datastack.top() == minstack.top())
minstack.pop();
datastack.pop();
minStack::getMin();
}
}
void minStack::push(int n)
{
cout<<"push("<<n<<"):\t";
datastack.push(n);
if(minstack.empty())
minstack.push(n);
else if(minstack.top()>=n)
minstack.push(n);
minStack::getMin();
}
void minStack::getMin()
{
if (minstack.empty())
cout<<"stack empty."<<endl;
else
cout <<"min in stack:" << minstack.top()<<endl;
}
int main()
{
minStack testStack;
testStack.push(3);
testStack.push(5);
testStack.push(2);
testStack.pop();
testStack.pop();
testStack.push(1);
testStack.pop();
testStack.pop();
testStack.pop();
return 0;
}