-
Notifications
You must be signed in to change notification settings - Fork 4
/
1-1.设计具有getMin()功能的栈.cpp
86 lines (73 loc) · 1.34 KB
/
1-1.设计具有getMin()功能的栈.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/***
设计一个具有getMin功能的栈
***/
#include <cstdio>
#include <stack>
using namespace std;
class StackWithMin {
public:
void push( int x );
void pop();
int top();
bool empty();
int getMin();
private:
stack<int> stackData;
stack<int> stackMin;
};
void StackWithMin::push( int x ) {
stackData.push( x );
if( stackMin.empty() ) {
stackMin.push( x );
}
else {
if( stackMin.top() >= x ) {
stackMin.push( x );
}
}
}
void StackWithMin::pop() {
if( stackData.empty() ) {
printf( "the stack is empty!" );
}
else {
int cur = stackData.top();
stackData.pop();
if( cur == stackMin.top() ) {
stackMin.pop();
}
}
}
int StackWithMin::getMin() {
if( stackData.empty() ) {
printf( "the stack is empty!" );
}
else {
return stackMin.top();
}
}
int StackWithMin::top() {
if( stackData.empty() ) {
printf( "the stack is empty!" );
}
else {
return stackData.top();
}
}
bool StackWithMin::empty() {
return stackData.empty();
}
int main() {
StackWithMin s;
s.push( 3 );
s.push( 4 );
s.push( 5 );
s.push( 1 );
s.push( 2 );
s.push( 1 );
s.pop();
s.pop();
s.pop();
printf( "%d\n", s.getMin() );
return 0;
}