[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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章