Stack containing the Min function

Source: Internet
Author: User

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

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.