Implement the following operations of a stack using queues.
Notes:
push to back, peek/pop from front, size, and is empty operations are valid.
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
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