Leetcode题目:Implement Stack using Queues

题目:Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

Notes:

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

 

题目解答:题目中要求使用队列来实现栈的功能。其中,对于队列只可以使用它的push,pop,size,empty操作。

代码为:

class Stack {
public:
    // Push element x onto stack.
    void push(int x) {
        if(q1.empty())
        {
            q2.push(x);
        }
        else
        {
            q1.push(x);
        }
    }

    // Removes the element on top of the stack.
    void pop() {
        if(q1.empty())
        {
            while(q2.size() > 1)
            {
                q1.push(q2.front());
                q2.pop();
            }
            if(q2.size() == 1)
                q2.pop();
        }
        else
        {
            while(q1.size() > 1)
            {
                q2.push(q1.front());
                q1.pop();
            }
            if(q1.size() == 1)
                q1.pop();
        }
    }

    // Get the top element.
    int top() {
        int tmp = -1;
        if(q1.empty())
        {
            while(q2.size() > 1)
            {
                q1.push(q2.front());
                q2.pop();
            }
            if(q2.size() == 1)
            {
                tmp = q2.front();
                q1.push(q2.front());
                q2.pop();
            }
        }
        else
        {
            while(q1.size() > 1)
            {
                q2.push(q1.front());
                q1.pop();
            }
            if(q1.size() == 1)
            {
                tmp = q1.front();
                q2.push(q1.front());
                q1.pop();
            }
        }
        return tmp;
    }

    // Return whether the stack is empty.
    bool empty() {
        return q1.empty() && q2.empty();
    }
private:
    queue<int> q1;
    queue<int> q2;
};

posted @ 2016-04-25 16:28  CodingGirl121  阅读(123)  评论(0编辑  收藏  举报