Use auxiliary stack to solve minimum stack

Insert picture description here

class MinStack {
    
    
 Stack<Integer> stack1;
 Stack<Integer> stack2;

 /** initialize your data structure here. */
 public MinStack() {
    
    
   stack1=new Stack<>();
   stack2=new Stack<>();;


 }

 public void push(int val) {
    
    
  if(stack1.empty()){
    
    
   stack1.push(val);
   stack2.push(val);
  }else {
    
    
   if(val<=stack2.peek()) stack2.push(val);
   stack1.push(val);
  }


 }

 public void pop() {
    
    
  if(!stack1.empty()){
    
    
   int t=stack1.pop();
   if(t==stack2.peek()) stack2.pop();
  }

 }

 public int top() {
    
    
  return stack1.peek();

 }

 public int getMin() {
    
    
  return stack2.peek();

 }
}

Guess you like

Origin blog.csdn.net/changbaishannefu/article/details/115179232