时间限制:1秒 空间限制:32768K 热度指数:158697
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
给出代码:
class Solution { public: void push(int value) { } void pop() { } int top() { } int min() { } };
一开始以为要手写栈,后面发现居然可以调用.....
获得最小栈的方法是在开始的时候建两个栈,遇到更小的就入栈,最后返回第二个栈的栈顶就可以了
实现代码:
class Solution { public: stack<int> sta; stack<int> stamin; void push(int value) { sta.push(value); if(stamin.empty()) { stamin.push(value); } else if(stamin.top() > value) { stamin.push(value); } } void pop() { if(stamin.top() == sta.top()) stamin.pop(); sta.pop(); } int top() { return sta.top(); } int min() { return stamin.top(); } };