码迷,mamicode.com
首页 > 编程语言 > 详细

包含min函数的栈(剑指offer,c++)

时间:2018-07-18 00:37:51      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:namespace   code   item   最小   turn   剑指offer   数据   c++   题目   

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <stack>
using namespace std;

class Solution {
public:

    void push(int value) {
        st.push(value);
        if(smin.empty())
        {
            smin.push(value);
        }
        if(smin.top()>value)
        {
            smin.push(value);
        }
    }
    void pop() {
        if(st.top()==smin.top())
        {
            smin.pop();
        }
        st.pop();
    }
    int top() {
        return st.top();
    }
    int min() {
        return smin.top();
    }
    private :
    stack<int> st;
    stack<int> smin;
};

int main()
{
     Solution s;
     s.push(2);
     s.push(1);
     s.push(3);
     s.push(4);
     s.push(4);
     s.push(5);
     s.push(3);
     cout<<s.top()<<endl;
     cout<<s.min()<<endl;
    return 0;
}

 

包含min函数的栈(剑指offer,c++)

标签:namespace   code   item   最小   turn   剑指offer   数据   c++   题目   

原文地址:https://www.cnblogs.com/dshn/p/9326757.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!