[leetcode] 225. Implement Stack using Queues 解题报告

题目链接:https://leetcode.com/problems/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 backpeek/pop from frontsize, 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).

Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.


思路:可以用两个队列模拟一个栈,我们把两个队列分别叫que1, que2,然后来看各个操作如何模拟。

1. 对于top,我们知道栈是先入后出,因此top会返回最后一个入栈的值,而这个值在队列的尾部。而我们不能得到尾部的值,所以可以将队列前面的值出队列并将出队列的值加入另一个队列中,而最后一个就是我们要的值。

2. 对于pop,和top的思想是一样的,只是剩下最后一个值将不入另一个队列。

3. 对于push,直接入队列即可。

4. 对于empty,如果两个队列都为空,则栈为空,否则不为空。

代码如下:

class Stack {
public:
    // Push element x onto stack.
    void push(int x) {
        que1.push(x);
    }

    // Removes the element on top of the stack.
    void pop() {
        while(que1.empty() == false)
        {
            int val = que1.front();
            que1.pop();
            if(que1.empty())
                return;
            else
                que2.push(val);
        }
        while(que2.empty() == false)
        {
            int val = que2.front();
            que2.pop();
            if(que2.empty())
                return;
            else
                que1.push(val);
        }
    }

    // Get the top element.
    int top() {
        while(que1.empty() == false)
        {
            int val = que1.front();
            que1.pop();
            que2.push(val);
            if(que1.empty())
                return val;
        }
        while(que2.empty() == false)
        {
            int val = que2.front();
            que2.pop();
            que1.push(val);
            if(que2.empty())
                return val;
        }
    }
    // Return whether the stack is empty.
    bool empty() {
        return que1.empty() && que2.empty();
    }
private:
    queue<int> que1;
    queue<int> que2;
};

参考:剑指offer中文版(这是我带到国外的唯一一本书 大笑





你可能感兴趣的:(LeetCode,算法,Queue,stack)