隊列實現棧,棧實現隊列

  很常見的兩道題:
1、用 queue 實現 stack:LeetCode - 225. Implement Stack using Queues
2、用 stack 實現 queue:LeetCode - 232. Implement Queue using Stacks

一、Implement Stack using Queues

  就是用 queue 來模擬 stack,實現 push、top、pop、empty 功能(值得注意的是,STL 裏的 pop 都是不返回值的,這裏需要返回 top 值),題目保證不會有空的時候出現 top 或者 pop 的調用(STL 裏的 queue 和 stack 在遇到這種情況時也只是運行時崩掉)。

1.1、用兩個 queue 模擬 stack

  用兩個 queue 模擬,很容易理解,就是始終保持一個 queue 是空的,push 就往另一個 queue 裏 push,然後 pop 的話就把不是空的 queue 一直往另一個原本是空的 queue 裏邊放,知道只剩一個元素,然後 pop 這個元素即可。代碼很好寫,也很常見,就不寫了。

1.2、用一個 queue 模擬 stack

  用一個 queue 的話,就是每次 push 一個數之後,把它前邊的數,重新 pop 並 push 會 queue 中,這樣每次新 push 的數就在 front 了,pop 和 top 就很方便了:

    queue<int> q;
    MyStack() {}
    
    void push(int x) {
        int cnt = q.size();
        q.push(x);
        while(cnt != 0) {
            const int t = q.front();
            q.pop();
            q.push(t);
            --cnt;
        }
    }
    
    int pop() {
        const int res = q.front();
        q.pop();
        return res;
    }
    
    int top() { return q.front(); }
    
    bool empty() { return q.empty(); }

二、Implement Queue using Stacks

  用 stack 模擬 queue,肯定是有兩個 stack,用一個做不到。就是一個用來進,一個用來出,如果出的 stack 是空,就把進的轉移到出的裏邊,然後出,push 永遠是往進的裏邊 push:

    stack<int> sin, sout;
    MyQueue() {}
    
    void push(int x) {
        sin.push(x);
    }
    
    int pop() {
        if(sout.empty()) {
            while(!sin.empty()) {
                const int t = sin.top();
                sin.pop();
                sout.push(t);
            }
        }
        const int res = sout.top();
        sout.pop();
        return res;
    }
    
    int peek() {
        if(sout.empty()) {
            while(!sin.empty()) {
                const int t = sin.top();
                sin.pop();
                sout.push(t);
            }
        }
        return sout.top();
    }
    
    bool empty() {
        return sin.empty() && sout.empty();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章