棧和隊列的應用場景:如何用棧實現隊列

題目

請你僅使用兩個棧實現先入先出隊列。隊列應當支持一般隊列的支持的所有操作(push、pop、peek、empty):

實現 MyQueue 類:

void push(int x) 將元素 x 推到隊列的末尾

int pop() 從隊列的開頭移除並返回元素

int peek() 返回隊列開頭的元素

boolean empty() 如果隊列為空,返回 true ;否則,返回 false

來源:力扣(LeetCode)

鏈接:
https://leetcode-cn.com/problems/implement-queue-using-stacks

著作權歸領扣網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

代碼

/**
 * https://leetcode-cn.com/problems/implement-queue-using-stacks/
 */
class MyQueue {
    Deque<Integer> inStack;
    Deque<Integer> outStack;
    /** Initialize your data structure here. */
    public MyQueue() {
        inStack = new LinkedList<>();
        outStack = new LinkedList<>();
    }
    /** Push element x to the back of queue. */
    public void push(int x) {
        inStack.push(x);
    }
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if (outStack.isEmpty()) {
            inStack2outStack();
        }
        return outStack.pop();
    }
    /** Get the front element. */
    public int peek() {
        if (outStack.isEmpty()) {
            inStack2outStack();
        }
        return outStack.peek();
    }
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return inStack.isEmpty() && outStack.isEmpty();
    }
    private void inStack2outStack() {
        while (!inStack.isEmpty()) {
            outStack.push(inStack.pop());
        }
    }
}

總結

* 這是一個非常常見的題目,棧的特性是先入後出,隊列的特性是先入先出。因此,我們可以用兩個棧來實現隊列,inStack記錄輸入,outStack記錄輸出,以上代碼巧妙的地方是在outStack為空的時候,將inStack的數據輸入進去。

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/222894.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-09 14:13
下一篇 2024-12-09 14:13

相關推薦

發表回復

登錄後才能評論