Define the data structure of the stack. Add a min function to obtain the minimum element of the stack.
The time complexity of the min, push, and pop functions is O (1 ).
# Include <deque> # include <assert. h> # include <iostream> using namespace STD; Template <typename T> class mystack {PRIVATE: deque <t> m_data; deque <size_t> m_minindex; public: // constructor mystack () {}// destructor virtual ~ Mystack () {}// empty int isempty () {return m_data.size () ;}// return the top element T & Top () {return m_data.back ();} // return the const T & Top () const {return m_data.back ();} // The Void push (const T & Value) {m_data.push_back (value ); if (m_minindex.size () = 0) {m_minindex.push_back (0);} else {If (value <m_data [m_minindex.back ()]) {m_minindex.push_back (m_data.size ()-1 );} else {m_minindex.push_back (m_minindex.back () ;}}// out-of-stack void POP () {m_data.pop_back (); m_minindex.pop_back () ;}// return the minimum const T & min () const {assert (m_data.size ()> 0); Assert (m_minindex.size ()> 0); Return m_data [m_minindex.back ()] ;}; int main (INT argc, char ** argv) {mystack <int> S; S. push (3); S. push (1); S. push (4); S. push (2); // print the stack while (S. isempty () {cout <S. top () <"outbound stack" <Endl; S. pop (); cout <"minimum value:" <S. min () <Endl ;}}