【剑指offer 面试题21】包含min函数的栈

思路:

  通过增加一个辅助栈保存每个状态对应的最小值。栈实现的不完整,应该还包含empty()等常规函数。

 1 #include <iostream>
 2 #include <stack>
 3 using namespace std;
 4 
 5 template <typename T> class StackWithMin
 6 {
 7 public:
 8     void push(const T& value);
 9     void pop();
10     T getMin();
11 
12 private:
13     stack<T> DataStack;
14     stack<T> MinStack;
15 };
16 
17 template <typename T> void StackWithMin<T>::push(const T& value)
18 {
19     DataStack.push(value);
20 
21     if(MinStack.size() == 0 || value < MinStack.top())
22         MinStack.push(value);
23     else
24         MinStack.push(MinStack.top());
25 }
26 
27 template <typename T> void StackWithMin<T>::pop()
28 {
29     DataStack.pop();
30     MinStack.pop();
31 }
32 
33 template <typename T> T StackWithMin<T>::getMin()
34 {
35     return MinStack.top();
36 }
37 
38 int main()
39 {
40     StackWithMin<int> s;
41 
42     cout<<"push 5"<<endl;
43     s.push(5);
44     cout<<"Min: "<<s.getMin()<<endl;
45 
46     cout<<"push 3"<<endl;
47     s.push(3);
48     cout<<"Min: "<<s.getMin()<<endl;
49 
50     cout<<"push 1"<<endl;
51     s.push(1);
52     cout<<"Min: "<<s.getMin()<<endl;
53 
54     cout<<"pop"<<endl;
55     s.pop();
56     cout<<"Min: "<<s.getMin()<<endl;
57 
58     cout<<"pop"<<endl;
59     s.pop();
60     cout<<"Min: "<<s.getMin()<<endl;
61 
62     cout<<"push 10"<<endl;
63     s.push(10);
64     cout<<"Min: "<<s.getMin()<<endl;
65 }

 

测试结果:

push 5
Min: 5
push 3
Min: 3
push 1
Min: 1
pop
Min: 3
pop
Min: 5
push 10
Min: 5

 

转载于:https://www.cnblogs.com/tjuloading/p/4595319.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值