包涵min函数的栈
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数
思路:用一个辅助栈动态维护最小值
1 class Solution { 2 public: 3 void push(int value) { 4 sta1.push(value); 5 if(sta2.size()==0 || sta2.top()>=value)sta2.push(value); 6 } 7 void pop() { 8 int tmp=sta1.top(); 9 sta1.pop(); 10 if(sta2.top()==tmp)sta2.pop(); 11 } 12 int top() { 13 return sta1.top(); 14 } 15 int min() { 16 return sta2.top(); 17 } 18 private: 19 stack<int> sta1; 20 stack<int> sta2; 21 };