剑指offer之【包含min函数的栈】

题目:

  包含min函数的栈

链接:

  https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49?tpId=13&tqId=11173&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目描述:

  定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

题目思路:

  定义两个栈: stk1一个正常的压入数据,stk2一个存储当前站内的最小数据

  要点:压入数据时,stk2是否为空,压入的数据是否比stk2栈顶小

     弹出数据时,是否为最小

代码:

  

 1 class Solution {
 2 public:
 3     void push(int value){
 4         if(minnum.empty())
 5               minnum.push(value);
 6         else if(value <= minnum.top())
 7               minnum.push(value);
 8         stk1.push(value);
 9     }
10 
11     void pop(){
12         if(stk1.top()==minnum.top()){
13             stk1.pop();
14             minnum.pop();
15         }
16         else{
17             stk1.pop();
18         }
19     }
20 
21     int top() {
22         return stk1.top();
23     }
24 
25     int min() {
26         return minnum.top();
27     }
28 private:
29     stack<int> stk1;
30     stack<int> minnum;
31 };
原文地址:https://www.cnblogs.com/wangshujing/p/6936536.html