包含min 函数的栈

来源:互联网 发布:js use strict的好处 编辑:程序博客网 时间:2024/05/05 08:43
/**设计包含min 函数的栈。定义栈的数据结构,要求添加一个min 函数,能够得到栈的最小元素。要求函数min、push 以及pop 的时间复杂度都是O(1)。*/
#include<stack>using namespace std;template<typename T>class StackWithMix{private:stack<T> data_stack;stack<T> min_stack;public:T minvalue(void){return min_stack.top();}void push(T integer);T pop(void);};template<typename T>void StackWithMix<T>::push(T integer){data_stack.push(integer);if(integer<min_stack.top() || min_stack.empty()){min_stack.push(integer);}else{min_stack.push(min_stack.top());}}template<typename T>T StackWithMix<T>::pop(){assert(!data_stack.empty());T ret = data_stack.top();data_stack.pop();min_stack.pop();return ret;}int _tmain(int argc, _TCHAR* argv[]){StackWithMix<int> stack_with_mix;stack_with_mix.push(6);stack_with_mix.push(11);stack_with_mix.push(3);stack_with_mix.push(8);stack_with_mix.push(1);stack_with_mix.push(19);stack_with_mix.pop();stack_with_mix.pop();printf("%d", stack_with_mix.minvalue());system("pause");}

0 0