Leetcode-225Implement Stack using Queues

225. Implement Stack using Queues

Implement the following operations of a stack using queues.

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

題解:

使用隊列實現棧:
首先,我們給出棧和隊列的特點:
棧(stack)中的數據是先進后出的(First In Last Out: FILO):
std::stack<int> S;
STL的棧頭文件:
#include <stack>
包括五種基本操作:
S.top(); // 取棧頂元素;
S.push(x); // 將x添加進棧;
S.pop(); // 彈出棧頂元素;
S.empty(); // 判斷棧是否為空;
S.size(); // 棧中元素的個數;
隊列(queue)中的數據是先進先出的(First In First Out: FIFO):
std::queue<int> Q;
STL的隊列頭文件:
#include <queue>
包括六種基本操作:
Q.front(); // 取隊列頭部元素;
Q.back(); // 取隊列尾部元素;
S.push(x); // 將x添加進隊列;
S.pop(); // 彈出隊列頭部元素;
S.empty(); // 判斷隊列是否為空;
S.size(); // 隊列中元素的個數;
下面我們來分析如何用列表來實現棧:

image.png

如圖:我們想要讓左側的queue來實現右側的stack,只需要讓隊列的元素以先進后出的方式存入隊列即可;所以我們要讓queue的元素存儲順序變更為new_queue的元素存儲順序。
我想到的解決辦法是,創建一個臨時列表tem_q來幫助q實現逆序存儲;
image.png

如圖,當存入一個元素3時:

  1. 將(元素3)push 到空的臨時隊列中;
  2. 將q中已逆序的元素依次取出存入temp_q中,直到取出q中所有元素(q為空);注:剛開始push第一個元素時,q本來就是空的,所以直接跳到三步;
  3. 將tem_q中逆序的元素依次取出存入q中,直到取出所有元素為止(tem_q為空);
    自此,后進入的(元素3)也成功變為隊列q的頭部元素,實現了后入先出(棧);

My Solution(C/C++完整實現):

#include <cstdio>
#include <iostream>
#include <queue>

using namespace std;

class MyStack {
public:
    /** Initialize your data structure here. */
    MyStack() {

    }
    /** Push element x onto stack. */
    void push(int x) {
        queue<int> tem_q;
        tem_q.push(x);
        while (!q.empty()) {
            tem_q.push(q.front());
            q.pop();
        }
        while (!tem_q.empty()) {
            q.push(tem_q.front());
            tem_q.pop();
        }
    }

    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int x = q.front();
        q.pop();
        return x;
    }

    /** Get the top element. */
    int top() {
        return q.front();
    }

    /** Returns whether the stack is empty. */
    bool empty() {
        return q.empty();
    }
private:
    queue<int> q;
};

int main() {
    MyStack s;
    s.push(1);
    s.push(2);
    s.push(3);
    while (!s.empty()) {
        printf("%d ", s.top());
        s.pop();
    }
    return 0;
}

結果:

3 2 1

My Solution(Python):

import queue
class MyStack:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.Q = queue.Queue()
        self.temp_Q = queue.Queue()

    def push(self, x):
        """
        Push element x onto stack.
        :type x: int
        :rtype: void
        """
        self.temp_Q.put(x)
        while self.Q.empty() is False:
            self.temp_Q.put(self.Q.get())
        while self.temp_Q.empty() is False:
            self.Q.put(self.temp_Q.get())

    def pop(self):
        """
        Removes the element on top of the stack and returns that element.
        :rtype: int
        """
        return self.Q.get()

    def top(self):
        """
        Get the top element.
        :rtype: int
        """
        # return self.Q.get()
        x = self.Q.get()
        self.push(x)
        return x

    def empty(self):
        """
        Returns whether the stack is empty.
        :rtype: bool
        """
        return self.Q.empty()


# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容