-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path30_Min_Stack.cpp
More file actions
101 lines (69 loc) · 1.61 KB
/
30_Min_Stack.cpp
File metadata and controls
101 lines (69 loc) · 1.61 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
//
// Created by mark on 2019/7/10.
// Copyright © 2019年 mark. All rights reserved.
//
/*
说明:
1. 问题:30.包含min函数的栈,定义栈的数据结构,在该类型中实现一个能得到栈的最小元素的min函数
2. 思路:调用一个辅助min栈,每次压栈的同时往min栈压入当前栈内的最小值(把之前最小值和当前最小值相比较的小者);
*/
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <cmath>
#include <string>
#include <assert.h>
using namespace std;
class minStack
{
public:
// 压栈操作
void push(int value)
{
s_data.push(value);
if(s_min.empty() || value < s_min.top())
s_min.push(value);
else
s_min.push(s_min.top());
}
// 出栈操作
void pop()
{
assert(s_data.size() > 0 && s_min.size() > 0);
s_data.pop();
s_min.pop();
}
// 返回栈顶元素
int top()
{
assert(s_data.size() > 0 && s_min.size() > 0);
return s_data.top();
}
// 返回栈中最小值
int min_top()
{
return s_min.top();
}
// 判空
bool empty()
{
return s_data.empty();
}
private:
stack<int> s_data; // 正常数据栈
stack<int> s_min; // 保存当前最小值栈
};
int main(){
minStack s;
s.push(4);
s.push(1);
s.push(2);
s.push(3);
int a = s.min_top();
s.pop();
int b = s.min_top();
cout << a << endl;
cout << b << endl;
return 0;
}