-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path21包含min函数的栈.cpp
49 lines (45 loc) · 1018 Bytes
/
21包含min函数的栈.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
//21
//定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
// 解法:辅助栈(存放最小值)
class Solution {
public:
void push(int value)
{
m_data.push(value);
if (m_min.empty())
m_min.push(value);
else
{
if (value < m_min.top())
m_min.push(value);
else
m_min.push(m_min.top());
}
}
void pop()
{
if (m_data.empty())
throw std::runtime_error("stack is empty!");
else
{
m_data.pop();
m_min.pop();
}
}
int top() //似乎比较多余??
{
if (m_data.empty())
throw std::runtime_error("stack is empty!");
else
return m_data.top();//????????
}
int min()
{
if (m_data.empty())
throw std::runtime_error("stack is empty!");
return m_min.top();
}
private:
stack<int> m_data;
stack<int> m_min;
};