书上给的代码有点问题,得按照他说的逻辑自己写,要注意以下两点:
  • stackPop不为空,stackPush不能压入stacjPop栈中
  • stackPush压入stacjPop栈中时,要一次性压完所有数据
所以书上的add代码要改,要加一个判断stackPop栈为空的判断。
peek和poll也要改,也是加判断,判断是否满足stackPop栈为空,stackPush不空。
就是这么多,其余直接抄书,以下是代码。
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void pushToPopStack(Stack<Integer> pushStack, Stack<Integer> popStack){
        while (!pushStack.empty()){
                int tmp = pushStack.pop();
                popStack.push(tmp);
        }

    }

    public static void main(String[] args) {
        Stack<Integer> stackPush;
        Stack<Integer> stackPop;
        stackPush = new Stack<>();
        stackPop = new Stack<>();
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();

        for(int i=0; i<n; i++) { // 注意 while 处理多个 case
            String s = in.next();
            if(Objects.equals(s, "add"))
            {
                int a = in.nextInt();
                stackPush.push(a);
                if(stackPop.isEmpty()){
                    pushToPopStack(stackPush, stackPop);
                }
       
            }
            else if(Objects.equals(s, "poll")) {
                if(stackPop.isEmpty() && !stackPush.isEmpty()){
                    pushToPopStack(stackPush, stackPop);
                }
                stackPop.pop();
//                System.out.println(stackPop.pop());
            }
            else if(Objects.equals(s, "peek")) {
                if(stackPop.isEmpty() && !stackPush.isEmpty()){
                    pushToPopStack(stackPush, stackPop);
                }
                System.out.println(stackPop.peek());
            }
            //pushToPopStack(stackPush, stackPop);
        }
    }
}