leetcode 225 Implement Stack using Queues C++

来源:互联网 发布:java常用工具 编辑:程序博客网 时间:2024/05/01 02:37

两个队列实现一个栈,核心思想就是压栈的时候,压入空的队列,然后把非空的队列的元素亚到后面去。

    queue<int> q1;    queue<int> q2;            void push(int x) {        if(q1.empty()&&q2.empty()){            q1.push(x);        }else if(q2.empty()){            q2.push(x);            while(!q1.empty()){                q2.push(q1.front());                q1.pop();            }        }else{            q1.push(x);            while(!q2.empty()){                q1.push(q2.front());                q2.pop();            }        }    }    // Removes the element on top of the stack.    void pop() {        if(!q1.empty()) q1.pop();        else if(!q2.empty()) q2.pop();    }    // Get the top element.    int top() {        if(!q1.empty()) return q1.front();        else if(!q2.empty()) return q2.front();        else return NULL;    }    // Return whether the stack is empty.    bool empty() {        return q2.empty()&&q1.empty();    }


0 0
原创粉丝点击