The stack __ function that contains the MIN function

Source: Internet
Author: User
Topic Description

To define the data structure of the stack, implement a min function that gets the minimum stack element in the type.

Found a lot of Java code than C + + short, Meow ~

Implement functions of several functions

Create a new auxiliary stack, so that the secondary stack from top to bottom storage should be the minimum value of-> secondary small value-> ... class Solution {public:     stack<int>
Datastack, Minstack;     void push (int val) {//press the element into the stack where the data is stored         datasta
        Ck.push (Val); When the stack of the smallest element is stored without elements, the current element is pressed into the minimum element stack.
Otherwise, first compare the size, press the smaller element into the smallest element stack.         if (Minstack.empty ()) {      
      minstack.push (Val); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}         else{ 
           int min = Minstack.top ();             val<=min?minstack.push (val):
Minstack.push (min);         }            
&NBSP;&NBSP;&NBSP}//pop, the data stack auxiliary stack pops up the top element.    &Nbsp;void pop () {        datastack.pop ();      
   minstack.pop (); &NBSP;&NBSP;&NBSP;&NBSP}     int Top () {        
return  Datastack.top (); &NBSP;&NBSP;&NBSP;&NBSP}     int min () {        
return Minstack.top ();     };



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.