【Leetcode】232.用栈实现队列

232 用栈实现队列

思路:

  • 准备两个栈,一个push栈,一个pop栈

  • 执行push操作时,只向push栈中添加元素

  • 执行pop操作时,若pop栈为空,则先将push栈中的元素全倒入到pop栈中,然后弹出pop栈的栈顶

  • 执行peek操作时,和pop操作基本相同

  • 当push栈和pop栈均为空时,队列为空

  • *代码:**

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    class MyQueue {
    private Stack<Integer> stackPop;
    private Stack<Integer> stackPush;
    /** Initialize your data structure here. */
    public MyQueue() {
    this.stackPop = new Stack<>();
    this.stackPush = new Stack<>();
    }

    /** Push element x to the back of queue. */
    public void push(int x) {
    stackPush.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
    //当pop栈为空时,将push栈中的元素都加入到pop栈中来
    if(stackPop.empty()){
    while(!stackPush.empty())
    stackPop.push(stackPush.pop());
    }
    //pop不空时,直接弹出pop栈的栈顶
    return stackPop.pop();
    }

    /** Get the front element. */
    //除了最后一行外,和pop操作基本一致
    public int peek() {
    //当pop栈为空时,将push栈中的元素都加入到pop栈中来
    if(stackPop.empty()){
    while(!stackPush.empty())
    stackPop.push(stackPush.pop());
    }
    return stackPop.peek();
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
    return stackPush.empty() && stackPop.empty();
    }
    }