# [Question 100] design a stack containing min Functions

Source: Internet
Author: User

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 ;}}

Related Keywords:

### Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.