3.4 Queue via Stacks

来源:互联网 发布:淘宝号登不上去 编辑:程序博客网 时间:2024/05/29 18:18

Using two stacks to implement queue.

class Queue {public:    stack<int> stkIn;    stack<int> stkOut;    // Push element x to the back of queue.    void push(int x) {        stkIn.push(x);    }    // Removes the element from in front of queue.    void pop(void) {        peek();        stkOut.pop();    }    // Get the front element.    int peek(void) {        if(stkOut.empty()){            while(stkIn.size()){                stkOut.push(stkIn.top());                stkIn.pop();            }        }        return stkOut.top();    }    // Return whether the queue is empty.    bool empty(void) {        return (stkOut.empty() && stkIn.empty());    }};
0 0