[232] Implement Queue using Stacks

1. 题目描述

Implement the following operations of a queue using stacks.

push(x) – Push element x to the back of queue.
pop() – Removes the element from in front of queue.
peek() – Get the front element.
empty() – Return whether the queue is empty.
Notes:
You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

使用栈实现队列。只能使用栈提供的push, peek/pop, size和empty方法。

2. 解题思路

栈和队列不同的地方在于,栈为后进先出,而队列为先进先出。也就是说,对于一个栈,只能看到当前栈顶的元素,但是对于队列,我们要看到位于当前栈中最深处的元素。但是当我们把一个栈翻转过来,栈中最深处的元素就变成了当前栈顶元素,再顺序出栈就能达到队列的效果。所以想法就是使用两个栈,一个栈保存正序列元素,另一个栈用来翻转这些元素。入队操作只需要push到正序列元素中,出队操作则先将正序列元素进行反转,再输出最上面的元素即可。值得一提的是,当前翻转过的栈不为空时,如果将正序列翻转后push进来就打乱了原有栈的顺序,所以需要加一个判断,当当前翻转栈有元素时直接出队即可。
双栈队列

3. Code

import java.util.Stack;

class MyQueue {
    Stack<Integer> forwardStack = new Stack<>();
    Stack<Integer> reverseStack = new Stack<>();

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

    // Removes the element from in front of queue.
    public void pop() {
        if(reverseStack.empty())
            doReverse();
        reverseStack.pop();
    }

    // Get the front element.
    public int peek() {
        if(reverseStack.empty())
            doReverse();
        return reverseStack.peek();
    }

    // Return whether the queue is empty.
    public boolean empty() {
        return forwardStack.size() == 0 && reverseStack.size() == 0;
    }

    /**
     * 翻转栈
     */
    private void doReverse()
    {
        while(!forwardStack.empty())
        {
            reverseStack.push(forwardStack.pop());
        }
    }
}
发布了79 篇原创文章 · 获赞 58 · 访问量 15万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章