输入: 6 push 3 push 2 push 1 getMin pop getMin 输出: 1 2
import java.util.Stack; import java.util.Scanner; class MyStack1{ private Stack<Integer> stackData; private Stack<Integer> stackMin; public MyStack1(){ this.stackData = new Stack<>(); this.stackMin = new Stack<>(); } public void push(int newNum){ if(this.stackMin.isEmpty()){ this.stackMin.push(newNum); } else if(newNum<=this.top()){ this.stackMin.push(newNum); } this.stackData.push(newNum); } public int pop(){ if(this.stackData.isEmpty()){ throw new RuntimeException("Your stack is empty."); } int value = this.stackData.pop(); if(value==this.top()){ this.stackMin.pop(); } return value; } public int top(){ return this.stackMin.peek(); } public int getMin(){ if(this.stackMin.isEmpty()){ throw new RuntimeException("Your stack is empty."); } return this.stackMin.peek(); } } public class Main{ public static void main(String[] args){ Scanner sc= new Scanner(System.in); MyStack1 mystack1 = new MyStack1(); int t = sc.nextInt(); for(int i=0;i<t;i++){ String op = sc.next(); if(op.equals("push")){ int x = sc.nextInt(); mystack1.push(x); }else if(op.equals("getMin")){ System.out.println(mystack1.getMin()); }else if(op.equals("pop")){ mystack1.pop(); } } } }
方法二:
import java.util.Stack; import java.util.Scanner; class MyStack2{ private Stack<Integer> stackData; private Stack<Integer> stackMin; public MyStack2(){ this.stackData = new Stack<>(); this.stackMin = new Stack<>(); } public void push(int newNum){ if(this.stackMin.isEmpty()){ this.stackMin.push(newNum); } else if(newNum<=this.getMin()){ this.stackMin.push(newNum); }else{ int newMin = this.stackMin.peek(); this.stackMin.push(newMin); } this.stackData.push(newNum); } public int pop(){ if(this.stackData.isEmpty()){ throw new RuntimeException("Your stack is empty."); } this.stackData.pop(); return this.stackMin.pop(); } public int getMin(){ if(this.stackMin.isEmpty()){ throw new RuntimeException("Your stack is empty."); } return this.stackMin.peek(); } } public class Main{ public static void main(String[] args){ Scanner sc= new Scanner(System.in); MyStack2 mystack2 = new MyStack2(); int t = sc.nextInt(); for(int i=0;i<t;i++){ String op = sc.next(); if(op.equals("push")){ int x = sc.nextInt(); mystack2.push(x); }else if(op.equals("getMin")){ System.out.println(mystack2.getMin()); }else if(op.equals("pop")){ mystack2.pop(); } } } }