Implement a stack, push,pop,min, and ensure time complexity is O (1)

Source: Internet
Author: User

#include <iostream> using namespace std;  struct stack        {         int* _pelem; // Pointer to element data          int _capacity;           int _top;             stack ( int n )                    :_capacity ( n)           {             _top = 0;              _pelem = new int [ _capacity];         }          ~stack () &NBSP;&NBsp;       {              delete []_pElem;              _pElem = NULL;         }              }; class Stack  {    private:     stack s;     stack minstack;  public:     stack (int n)                :s ( n)                 , minstack ( n)      {}       bool pop ()      {            if  (s._top == 0)              return  False ;          size_t value = s._pelem [--s._top];         //determines if the minimum element will be popped   if it is   updates the minimum element stack           if  (Value == minstack._pelem[minstack._top-1])              --minstack._top;           return true ;     }       bool push ( int value )      {          if  (s._top == s._capacity)               return false ;              if  (minstack._top==0 | | &NBSP;VALUE&NBSP;&LT;=MINSTACK._PELEM[MINSTACK._TOP-1])               minstack._pElem[minstack._top++] = value;           s._pElem[s._top++] = value;          return true ;     }        Int min ()      {         if  ( minstack._top == 0)               Return null ;        int pmin = minstack._ pelem[minstack._top-1];        return pmin;      } };


Implement a stack, push,pop,min, and ensure time complexity is O (1)

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.