(beginner) 8. Minimum stack

Source: Internet
Author: User

Design a stack that supports PUSH,POP,TOP operations and can retrieve the smallest elements within a constant time.

    • Push (x)-pushes element x into the stack.
    • Pop ()--Removes the element at the top of the stack.
    • Top ()--Gets the top element of the stack.
    • Getmin ()--retrieves the smallest element in the stack.

Example:

MinStack minStack = new MinStack();minStack.push(-2);minStack.push(0);minStack.push(-3);minStack.getMin();   --> 返回 -3.minStack.pop();minStack.top();      --> 返回 0.minStack.getMin();   --> 返回 -2.

Implemented using two stacks, one stack to store push-in data sequentially, and the other to save the minimum value that has occurred.

The Golang code is as follows:

Package Stackimport ("Container/list") type Stack struct {list *list. List}func Newstack () *stack {list: = list. New () return &stack{list}}func (Stack *stack) Push (value interface{}) {Stack.list.PushBack (value)}func (Stack *    Stack) Pop () interface{} {e: = Stack.list.Back () if E! = nil {stack.list.Remove (e) return E.value     } return Nil}func (Stack *stack) Peak () interface{} {e: = Stack.list.Back () if E! = Nil {return E.value } return Nil}func (Stack *stack) Len () int {return stack.list.Len ()}func (Stack *stack) Empty () bool {retur n Stack.list.Len () = = 0}/** * Your Minstack object would be instantiated and called as such: * obj: = Constructor (); * obj. Push (x); * obj. Pop (); * Param_3: = obj. Top (); * Param_4: = obj. Getmin (); */type minstack struct {s1, s2 *stack}/** Initialize your data structure here. */func Constructor () minstack {return minstack{s1:newstack (), S2:newstack (),}}func (thiS *minstack) Push (x int) {This.s1.Push (x) if This.s2.Empty () | | x <= this.s2.Peak (). ( int) {This.s2.Push (x)}}func (this *minstack) Pop () {x: = This.s1.Pop () if x = = This.s2.Peak (). ( int) {This.s2.Pop ()}}func (this *minstack) Top () int {return this.s1.Peak (). ( int)}func (this *minstack) getmin () int {return this.s2.Peak (). ( int)}
Related Article

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.