2023年1月11日 星期三

232. Implement Queue using Stacks

解題思路

用兩個 stack 來模擬,一個用來 push 的時候能塞到最後,一個用來 pop 的時候能拿到最前面的值。

注意每次都要先確保把另一個 stack 的東西搬過來。

程式碼

class MyQueue {
public:
    stack<int> s1; // for push
    stack<int> s2; // for pop

    MyQueue() {
        
    }
    
    void push(int x) {
        while(!s2.empty())
        {
            s1.push(s2.top());
            s2.pop();
        }
        s1.push(x);
    }
    
    int pop() {
        while(!s1.empty())
        {
            s2.push(s1.top());
            s1.pop();
        }
        int top = s2.top();
        s2.pop();
        return top;
    }
    
    int peek() {
        while(!s1.empty())
        {
            s2.push(s1.top());
            s1.pop();
        }
        return s2.top();
    }
    
    bool empty() {
        return s1.empty() && s2.empty();
    }
};

沒有留言:

張貼留言