Implement the following operations of a queue using stacks.
Notes:
push to top, peek/pop from top, size, and is empty operations are valid.
Subscribe to see which companies asked this question
class Queue { public: // Push element x to the back of queue. void push(int x) { s1.push(x); } // Removes the element from in front of queue. void pop(void) { if (s2.empty() && !s1.empty()) { while (!s1.empty()) { s2.push(s1.top()); s1.pop(); } } s2.pop(); } // Get the front element. int peek(void) { if (s2.empty() && !s1.empty()) { while (!s1.empty()) { s2.push(s1.top()); s1.pop(); } } return s2.top(); } // Return whether the queue is empty. bool empty(void) { return s1.empty() && s2.empty(); } private: std::stack<int> s1; std::stack<int> s2; };
[LeetCode]94. Implement Queue using Stacks用栈实现队列
原文:http://www.cnblogs.com/aprilcheny/p/4976843.html