[LeetCode] 225、キューの実装スタック

タイトル説明

スタックは、キューで達成しました

参照コード

類似タイトル:[LeetCode] 232、スタックキューと、簡単な質問。

bool g_invalidInput = false;
class MyStack {
public:
    /** Initialize your data structure here. */
    MyStack() {
        // nothing
    }
    
    /** Push element x onto stack. */
    void push(int x) {
        if(!q1.empty())
            q1.push(x);
        else
            q2.push(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        if(!q1.empty()){
            int num = q1.size();
            while(num != 1){
                q2.push(q1.front());
                q1.pop();
                num--;
            }
            
            int res = q1.front();
            q1.pop();
            return res;
        }else{
            int num = q2.size();
            while(num != 1){
                q1.push(q2.front());
                q2.pop();
                num--;
            }
            
            int res = q2.front();
            q2.pop();
            return res;            
        }
        
        g_invalidInput = true;
        return -1;
    }
    
    /** Get the top element. */
    int top() {
        if(!q1.empty()){
            int num = q1.size();
            while(num != 1){
                q2.push(q1.front());
                q1.pop();
                num--;
            }
            
            int res = q1.front();
            q2.push(res);
            q1.pop();
            return res;
        }else{
            int num = q2.size();
            while(num != 1){
                q1.push(q2.front());
                q2.pop();
                num--;
            }
            
            int res = q2.front();
            q1.push(res);
            q2.pop();
            return res;
        }
        
        g_invalidInput = true;
        return -1;        
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        if(q1.empty() && q2.empty())
            return true;
        else
            return false;
    }
    
private:
    queue<int> q1, q2;
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */
415元記事公開 ウォンの賞賛603 ビュー150,000 +を

おすすめ

転載: blog.csdn.net/ft_sunshine/article/details/104064161