LeetCode Implement Stack using Queues 栈&队列

来源:互联网 发布:儿童英语音乐软件 编辑:程序博客网 时间:2024/06/11 16:51

思路:

用两个队列互相导来实现一个栈。

c++ code:

class Stack {private:    int cur = 0;    queue<int> q[2];public:    // Push element x onto stack.    void push(int x) {        q[cur].push(x);    }    // Removes the element on top of the stack.    void pop() {        while(q[cur].size() > 1) {            q[1 - cur].push(q[cur].front());            q[cur].pop();        }        q[cur].pop();        cur = 1 - cur;    }    // Get the top element.    int top() {        while(q[cur].size() > 1) {            q[1 - cur].push(q[cur].front());            q[cur].pop();        }        int v = q[cur].front();        q[1-cur].push(q[cur].front());        q[cur].pop();        cur = 1 - cur;        return v;    }    // Return whether the stack is empty.    bool empty() {        return q[cur].empty();    }};
0 0
原创粉丝点击