Leetcode Implement Queue using Stacks

来源:互联网 发布:oracle数据库查询语句 编辑:程序博客网 时间:2024/06/07 22:15

题意:用堆栈模拟队列。

思路:简单模拟。

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


0 0