Leetcode 155. Min Stack Java language

Source: Internet
Author: User

Design a stack that supports push, POPs, top, and retrieving the minimum element in constant Time.push (x)--Push element X  Onto Stack.pop ()--Removes the element on top of the Stack.top ()--Get the top element.getmin ()--Retrieve the minimum element in the stack.   Example:minstack minstack = new Minstack () Minstack.push ( -2); Minstack.push (0); Minstack.push ( -3); Minstack.getmin ();      --Returns-3.minstack.pop (); Minstack.top ();   --Returns 0.minstack.getmin (); --Returns-2.subscribe to see which companies asked this question.

Test instructions: Design a stack with the Min function.

Public class minstack {    private stack<integer> stackdata ;    private stack<integer> stackmin;    /**  Initialize your data structure here. */    public minstack ()  {        stackData=new Stack<Integer> ();         stackMin=new Stack<Integer> ();    }         public void push (int x)  {         if (Stackmin.isempty ()) {             stackmin.push (x);         }else if (x<= Stackmin.peek ()) {            stackmin.push (x);         }        stackdata.push (x);    }     /////here seems a bit of a problem .... Packaging class comparison ....     public void pop ()  {        if ( Stackdata.peek (). Equals (Stackmin.peek ())) {             stackmin.pop ();        }         stackdata.pop ();     }        public  int top ()  {        return stackdata.peek ();     }        public int getmin ()  {         return stackmin.peek ();     }}/** *  your minstack object will be instantiated and caLled as such: * minstack obj = new minstack ();  * obj.push (x) ;  * obj.pop ();  * int param_3 = obj.top ();  * int param_4  = obj.getmin ();  */

PS: Defines a secondary stack. The minimum value to hold for each step. See also left teacher's book P1.

Leetcode 155. Min Stack Java language

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.