力扣记录:栈与队列1——232 用栈实现队列

本次题目

  • 232 用栈实现队列

232 用栈实现队列

  • 使用两个栈:一个输入栈,一个输出栈。
  1. push时直接将数据压入输入栈,当pop时需要进行判断,如果输出栈为空,则将输入栈中的所有数据按弹出顺序压入输出栈,然后pop;如果输入栈不为空则直接pop。
  2. 判断栈顶元素peek同上述pop前,当输入栈和输出栈都为空时队列为空。
  • 注意:在类中定义两个栈的数据结构,在初始化函数中进行初始化。
class MyQueue {
    //定义数据结构
    Stack<Integer> stackIn;
    Stack<Integer> stackOut;

    public MyQueue() {
        //使用两个栈:一个输入栈,一个输出栈
        stackIn = new Stack<>();
        stackOut = new Stack<>();
    }
    
    public void push(int x) {
        //push时直接将数据压入输入栈
        stackIn.push(x);
    }
    
    public int pop() {
        //当pop时需要进行判断
        //如果输出栈为空,则将输入栈中的所有数据按弹出顺序压入输出栈
        if(stackOut.isEmpty()){
            while(!stackIn.isEmpty()){
                stackOut.push(stackIn.pop());
            }
        }
        //然后pop,如果输入栈不为空则直接pop
        return stackOut.pop();
    }
    
    public int peek() {
        //判断栈顶元素同pop弹出前
        int res = this.pop();
        //pop后要push回输出栈
        stackOut.push(res);
        return res;
    }
    
    public boolean empty() {
        //当输入栈和输出栈都为空时队列为空
        return stackIn.isEmpty() && stackOut.isEmpty();
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

你可能感兴趣的:(java,算法)