232. 用栈实现队列

class MyQueue {

/** Initialize your data structure here. */
private final Deque<Integer> input;
private final Deque<Integer> outout;
private int size = 0;
public MyQueue() {
    input = new ArrayDeque<>();
    outout = new ArrayDeque<>();

}

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

/** Removes the element from in front of queue and returns that element. */
public int pop() {
    if (size == 0)  return -1;
    if (outout.isEmpty()) refresh();
    size--;
    return outout.pop();
}

private void refresh() {
    while (!input.isEmpty()){
        outout.push(input.pop());
    }
}

/** Get the front element. */
public int peek() {
    if (size == 0)  return -1;
    if (outout.isEmpty()) refresh();
    return outout.peek();
}

/** Returns whether the queue is empty. */
public boolean empty() {
    return size == 0;
}

}

posted @ 2021-01-02 17:10  backTraced  阅读(45)  评论(0)    收藏  举报