【LeetCode-简单题KMP】232. 用栈实现队列

题目

在这里插入图片描述

方法一:用输入栈和输出栈模拟队列

  1. 只有输出栈为空的时候才能将输入栈的元素补充到输出栈,
  2. 否则输出栈不为空,如果再从输入栈往输出栈填充元素,就会弄乱队列的先进先出规则,
  3. 而且当输出栈为空需要从输入栈补充元素时,必须一次性将输入栈的元素都弹出并且加到输出栈

在这里插入图片描述

class MyQueue {
    
    
    Stack<Integer> inStack;//入栈
    Stack<Integer> outStack;//出栈
    public MyQueue() {
    
    
          inStack = new Stack<>();
          outStack = new Stack<>();
    }
    //入队
    public void push(int x) {
    
    
        inStack.push(x);
    }
    //出队
    public int pop() {
    
    
        dumpstackIn(); // 如果stackOut为空,那么将stackIn中的元素全部放到stackOut中
        return outStack.pop();
    }
    //队首元素
    public int peek() {
    
    
        dumpstackIn(); // 如果stackOut为空,那么将stackIn中的元素全部放到stackOut中
        return outStack.peek();
    }
    //判空
    public boolean empty() {
    
    
     return inStack.isEmpty() && outStack.isEmpty();
    }

    // 如果stackOut为空,那么将stackIn中的元素全部放到stackOut中
    private void dumpstackIn(){
    
    
        if (!outStack.isEmpty()) return; //如果输出栈 有元素  则不需要将输入栈的元素放到输出栈
        while (!inStack.isEmpty()){
    
     //否则 输出栈没有元素,那么当执行pop 或peek的时候 ,就需要把输入栈的元素逆序放到输出栈供pop 或peek使用
                outStack.push(inStack.pop());
        }
    }
}

/**
 * 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();
 */

猜你喜欢

转载自blog.csdn.net/weixin_45618869/article/details/132948571