Title: Defines the data structure of the stack, requiring the addition of a min function to get the smallest element of the stack. The time complexity required for the function min, push, and Pop is O (1).
Ideas:
Define two stacks, one stack data for normal press, eject data, another stack min, press into the current minimum number, pop up when the smallest number
When pressed into the stack, if the pressed data is less than the smallest number in the current stack (recorded as Premin), then the value is pressed into, otherwise, the first minimum number (premin) is pressed, so that the top of the min stack is always the smallest number, the Min function directly return. And the pop-up stack when the two stack all pop-up.
Implementation code:
The Mystack class defined below is the concrete implementation class for the stack containing the Min function
#include <iostream>#include<stack>#include<assert.h>using namespacestd;template<typename t>classmystack{ Public: //Mystack (); voidMypush (Constt&value); voidMypop (); Constt&mymin ();Private: Stack<T> data,min;//The data stack is used to store each of the incoming stacks normally, and the min stack is used to store the smallest data in the current stack.};//the implementation of the push function, data stack normal input, min stack into the current stack of the smallest dataTemplate <typename t>voidMystack<t>::mypush (Constt&value) {Data.push (value); //If there is no data in the min stack or value is less than the minimum data (top) of the current stack, value enters the min stack if(min.size () = =0|| value<min.top ()) Min.push (value); //otherwise, the min stack entry is the original stack of the smallest data (top) ElseMin.push (Min.top ());}//pop function implementation, data,min stack normal popup dataTemplate <typename t>voidMystack<t>:: Mypop () {if(Data.size () >0&& min.size () >0) {data.pop (); Min.pop (); } Else{cout<<"stack is empty cannot eject data! "<<Endl; }}//min function implementation, get the smallest data in the current stackTemplate <typename t>Constt& mystack<t>:: Mymin () {//determine the condition, if the value is False, print the error message and terminate the programASSERT (Data.size () >0&& min.size () >0); returnmin.top ();}
Test the code and run the results:
int Main () { mystack<int> s; S.mypush (3); S.mypush (4); S.mypush (2); S.mypush (1); S.mypop (); S.mypop (); cout<<" the smallest element in this stack is:"<<s.mymin () <<Endl; return 0 ;}
Stack containing the Min function