Implement Queue using Stacks

来源:互联网 发布:配音视频软件 编辑:程序博客网 时间:2024/05/17 10:39

解决问题的思路:用两个栈,其中一个栈只是用来作缓存,每次操作结束都为空栈。

代码如下:

class Queue {private:    stack<int> stack1;    stack<int> buf;public:    // Push element x to the back of queue.    void push(int x) {        for(; !stack1.empty(); ) {            buf.push(stack1.top());            stack1.pop();        }        stack1.push(x);        for(; !buf.empty(); ) {            stack1.push(buf.top());            buf.pop();        }    }    // Removes the element from in front of queue.    void pop(void) {        stack1.pop();    }    // Get the front element.    int peek(void) {        return stack1.top();    }    // Return whether the queue is empty.    bool empty(void) {        return stack1.empty();    }};
0 0
原创粉丝点击