首页 > 其他 > 详细

[LeetCode]95. Implement Stack using Queues用队列实现栈

时间:2015-11-19 13:03:57      阅读:262      评论:0      收藏:0      [点我收藏+]

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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.

 

Subscribe to see which companies asked this question

 
解法:和题目Implement Queue using Stacks用栈实现队列相似,本题反过来用队列实现栈。方法相同,使用两个队列。需要注意的一点是,在top()操作中,不论是对哪一个队列操作,在取得队尾元素后都还需要将这个队尾元素移到另一个队列中,以保持顺序一致。
class Stack {
public:
    // Push element x onto stack.
    void push(int x) {
        while (!q2.empty()) {
            q1.push(q2.front());
            q2.pop();
        }
        q1.push(x);
    }
    // Removes the element on top of the stack.
    void pop() {
        if (!q1.empty()) {
            while (q1.size() > 1) {
                q2.push(q1.front());
                q1.pop();
            }
            q1.pop();
        }
        else {
            while (q2.size() > 1) {
                q1.push(q2.front());
                q2.pop();
            }
            q2.pop();
        }
    }
    // Get the top element.
    int top() {
        if (!q1.empty()) {
            while (q1.size() > 1) {
                q2.push(q1.front());
                q1.pop();
            }
            int ret = q1.front();
            q2.push(ret); // 注意必须将这个top也移到另一个队列
            q1.pop();
            return ret;
        }
        else {
            while (q2.size() > 1) {
                q1.push(q2.front());
                q2.pop();
            }
            int ret = q2.front();
            q1.push(ret); // 注意必须将这个top也移到另一个队列
            q2.pop();
            return ret;
        }
    }
    // Return whether the stack is empty.
    bool empty() {
        return q1.empty() && q2.empty();
    }
private:
    std::queue<int> q1;
    std::queue<int> q2;
};

 

[LeetCode]95. Implement Stack using Queues用队列实现栈

原文:http://www.cnblogs.com/aprilcheny/p/4977071.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!