[LeetCode]Implement Queue using Stacks

来源:互联网 发布:阿里巴巴数据库在哪 编辑:程序博客网 时间:2024/06/13 08:19

解题思路:

堆栈与队列的区别在于堆栈是先进后出,队列是先进先出。 所以要用堆栈实现一个队列的push,pop, peak和empty的基本思想就是将堆栈的进口和出口当成队列的出口,将堆栈的底当成队列的进口。

class Queue {private:    stack<int> s;public:    // Push element x to the back of queue.    void push(int x) {        stack<int> tem;        while(!s.empty())        {            int tem_int = s.top();            tem.push(tem_int);            s.pop();        }        s.push(x);        while(!tem.empty())        {            int tem_int = tem.top();            s.push(tem_int);            tem.pop();        }    }    // Removes the element from in front of queue.    void pop(void) {        s.pop();    }    // Get the front element.    int peek(void) {        return s.top();    }    // Return whether the queue is empty.    bool empty(void) {        return s.empty();    }};


0 0
原创粉丝点击