232. Implement Queue using Stacks

来源:互联网 发布:windows 10 dpi 编辑:程序博客网 时间:2024/06/05 00:18

title

Implement the following operations of a queue using stacks.

  • push(x) – Push element x to the back of queue.
  • pop() – Removes the element from in front of queue.
  • peek() – Get the front element.
  • empty() – Return whether the queue is empty.

Notes:

  • You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

solution

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

run time: 0ms

2个stack

0 0