Question: design a stack containing min functions.
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 ).
File distribution:
Header file and main file
Header file: Code
# Include <stack> # include <assert. h> using namespace STD; Template <typename T> class stackwithmin {PRIVATE: Stack <t> m_data; stack <t> m_min; public: stackwithmin () {} virtual ~ Stackwithmin () {} const T & Top (); T & Top () const; void push (const T & value); void POP (); const T & min () const; bool empty () const; int size () const ;}; // The inbound stack template <typename T> void stackwithmin <t >:: push (const T & value) {// new element into the stack m_data.push (value); // minimum value into the stack if (m_min.size () = 0 | value <m_min.top () m_min.push (value ); elsem_min.push (m_min.top () ;}// out-stack template <typename T> void stackwithmin <t >:: POP () {assert (m_data.size ()> 0 & m_min.size ()> 0); m_data.pop (); m_min.pop ();} // obtain the minimum element template <typename T> const T & stackwithmin <t> :: min () const {assert (m_data.size ()> 0 & m_min.size ()> 0); Return m_min.top ();} // get the top element of the stack and return the normal value template <typename T> T & stackwithmin <t >:: top () const {return m_data ;} // obtain the top element of the stack and return the commonly referenced template <typename T> const T & stackwithmin <t >:: top () {return m_data ;} // size template <typename T> int stackwithmin <t >:: size () const {return m_data.size ();} // whether the template is empty <typename T> bool stackwithmin <t>: Empty () const {return m_data.empty ();}
Main file: Code
# Include <iostream> # include <stack> # include <assert. h> # include "minstack. H "using namespace STD; int main () {stackwithmin <int> data; data. push (3); cout <data. min () <"; data. push (2); cout <data. min () <"; data. push (3); cout <data. min () <"; data. push (2); cout <data. min () <"; return 0 ;}
Running result: