20、剑指offer--包含min函数的栈

题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
 
解题思路:
1)本题定义一个数据栈m_data,正常的push、pop、top操作
2)定义辅助栈m_min保证每次栈顶元素都是最小元素,且和数据栈中元素的数目相同
 1 #include <iostream>
 2 #include <stack>
 3 using namespace std;
 4 class Solution {
 5 public:
 6     void push(int value) {
 7         m_data.push(value);
 8         if(m_min.size()==0 || value<m_min.top())
 9         {
10             m_min.push(value);
11         }
12         else
13         {
14             m_min.push(m_min.top());//目的每次栈顶都是最小的,并且保证两个栈中的数目相同
15                                     //这样,数据栈弹出元素,无需判断辅助栈,辅助栈也弹出
16         }
17     }
18     void pop() {
19         m_data.pop();
20         m_min.pop();
21     }
22     int top() {
23         return m_data.top();
24     }
25     int min() {
26         return m_min.top();
27     }
28 private:
29     stack<int> m_data;//数据栈
30     stack<int> m_min;//辅助栈
31 };
32 
33 int main()
34 {
35     Solution s;
36     s.push(3);
37     s.push(4);
38     s.push(5);
39     s.push(1);
40     s.push(2);
41     cout<<"最小值为:"<<s.min()<<endl;
42     s.pop();
43     s.pop();
44     cout<<"最小值为"<<s.min()<<endl;
45 }

原文地址:https://www.cnblogs.com/qqky/p/6877073.html