美文网首页
Implement Stack using Queues

Implement Stack using Queues

作者: 我叫胆小我喜欢小心 | 来源:发表于2017-04-22 11:40 被阅读19次

题目来源
使用队列来实现栈,我一开始先入为主的想法就是用两个队列来实现,push进一个,就把这个元素push进一个空队列,然后把另一个队列的元素一次出对再入刚push进一个元素的队列。还得判断一下当前哪个队列为空,冗长又复杂。
代码如下:

class MyStack {
public:
    /** Initialize your data structure here. */
    MyStack() {
        cur = 1;
    }
    
    /** Push element x onto stack. */
    void push(int x) {
        if (cur == 1) {
            q1.push(x);
            while (!q2.empty()) {
                int tmp = q2.front();
                q2.pop();
                q1.push(tmp);
            }
            cur = 2;
        }
        else {
            q2.push(x);
            while (!q1.empty()) {
                int tmp = q1.front();
                q1.pop();
                q2.push(tmp);
            }
            cur = 1;
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        if (cur == 1 && !q2.empty()) {
            int tmp = q2.front();
            q2.pop();
            return tmp;
        }
        if (cur == 2 && !q1.empty()) {
            int tmp = q1.front();
            q1.pop();
            return tmp;
        }
        return 0;
    }
    
    /** Get the top element. */
    int top() {
        if (cur == 1 && !q2.empty()) {
            return q2.front();
        }
        if (cur == 2 && !q1.empty()) {
            return q1.front();
        }
        return 0;
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        if (q1.empty() && q2.empty())
            return true;
        return false;
    }
private:
    int cur;
    queue<int> q1;
    queue<int> 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();
 */

然后实际上一个队列就可以了,每次push的时候先push,然后把之前的出队列再入队列。代码如下:

class MyStack {
public:
    /** Initialize your data structure here. */
    MyStack() {
    }
    
    /** Push element x onto stack. */
    void push(int x) {
        q.push(x);
        for (int i=0; i<q.size()-1; i++) {
            int tmp = q.front();
            q.pop();
            q.push(tmp);
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int tmp = q.front();
        q.pop();
        return tmp;
    }
    
    /** Get the top element. */
    int top() {
        return q.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q.empty();
    }
private:
    int cur;
    queue<int> q;
};

/**
 * 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();
 */

相关文章

网友评论

      本文标题:Implement Stack using Queues

      本文链接:https://www.haomeiwen.com/subject/huhszttx.html