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)}