1.2由两个栈组成的队列

题目

编写一个类,用两个栈实现,支持队列的基本操作(add、poll、peek)。

思路

一个栈作为压入栈,另一个栈作为弹出栈。

要做到:

  1. 如果stackPush要往stackPop中压入数据,那么必须一次性把stackPush中的数据全部压入。
  2. 如果stackPop不为空,stackPush绝对不能向stackPop中压入数据。
代码实现
public class TwoStacksQueue {
    public Stack<Integer> stackPush;
    public Stack<Integer> stackPop;

    public TwoStacksQueue() {
        stackPush = new Stack<>();
        stackPop = new Stack<>();
    }

    public void add(int pushInt) {
        stackPush.push(pushInt);
    }

    public int poll() {
        if (stackPush.isEmpty() && stackPop.isEmpty()) {
            throw new RuntimeException("Queue is empty!");
        } else if (stackPop.isEmpty()) {
            while (!stackPush.isEmpty()) {
                stackPop.push(stackPush.pop());
            }
        }

        return stackPop.pop();
    }

    public int peek() {
        if (stackPush.isEmpty() && stackPop.isEmpty()) {
            throw new RuntimeException("Queue is empty!");
        } else if (stackPop.isEmpty()) {
            while (!stackPush.isEmpty()) {
                stackPop.push(stackPush.pop());
            }
        }

        return stackPop.peek();
    }
}

你可能感兴趣的:(《程序员代码面试指南》学习笔记)