publicclassMinStack{/** initialize your data structure here. */intmin;Stack<Integer>stack;publicMinStack(){stack=newStack<Integer>();min=Integer.Max_VALUE;}publicvoidpush(intx){// only push the old minimum value when the current // minimum value changes after pushing the new value xif(x<=min){stack.push(min);min=x;}stack.push(x);}publicvoidpop(){// if pop operation could result in the changing of the current minimum value, // pop twice and change the current minimum value to the last minimum value.if(stack.peek()==min){stack.pop();min=stack.pop();}elsestack.pop();if(stack.empty())min=Integer.MAX_VALUE;}publicinttop(){returnstack.peek();}publicintgetMin(){returnmin;}}/** * 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(); */
classMinStack(object):def__init__(self):# do some intialize if necessaryself.stack=[]self.minstack=[]defpush(self,number):# write yout code hereself.stack.append(number)iflen(self.minstack)==0ornumber<=self.minstack[-1]:self.minstack.append(number)defpop(self):# pop and return the top item in stackifself.stack[-1]==self.minstack[-1]:self.minstack.pop()returnself.stack.pop()deftop(self):returnself.stack[-1]defgetMin(self):# return the minimum number in stackreturnself.minstack[-1]