Topic
Define the data structure of the stack, implement a min function in the type that can get the smallest element of the stack. In this stack, the time complexity of calling Min,push and POPs is O (1).
Ideas
Using two stacks, a data stack is used to hold the data, and a secondary stack is used to hold the minimum value.
#include <stack>#include <assert.h>Template<TypeNameT>classstackwithmin{ Public: Stackwithmin (void) {}Virtual~stackwithmin (void) {} t& Top (void);Constt& Top (void)Const;voidPushConstt& value);voidPopvoid);Constt& min (void)Const;BOOLEmpty ()Const; size_t size ()Const;Private:STD:: Stack<T>m_data;//data stack, all elements of the stack STD:: Stack<T>M_min;//auxiliary stack, the smallest element of the stack};Template<TypeNameT>voidStackwithmin<t>::p Ush (Constt& value) {//Add new elements to the secondary stackM_data.push (value);The new element is inserted into the auxiliary stack when the new element is less than the minimum element of the previous hour; //Otherwise insert the previous minimum element into the secondary stack again if(m_min.size () = =0|| Value < M_min.top ()) M_min.push (value);ElseM_min.push (M_min.top ());}Template<TypeNameT>voidStackwithmin<t>::p op () {Assert (M_data.size () >0&& m_min.size () >0); M_data.pop (); M_min.pop ();}Template<TypeNameT>Constt& Stackwithmin<t>::min ()Const{Assert (M_data.size () >0&& m_min.size () >0);returnM_min.top ();}Template<TypeNameT> t& Stackwithmin<t>::top () {returnM_data.top ();}Template<TypeNameT>Constt& Stackwithmin<t>::top ()Const{returnM_data.top ();}Template<TypeNameT>BOOLStackwithmin<t>::empty ()Const{returnM_data.empty ();}Template<TypeNameT> size_t stackwithmin<t>::size ()Const{returnM_data.size ();}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Stack containing the Min function