请用栈实现一个队列,支持如下四种操作:
- push(x) – 将元素x插到队尾;
- pop() – 将队首的元素弹出,并返回该元素;
- peek() – 返回队首元素;
- empty() – 返回队列是否为空;
class MyQueue { public: /** Initialize your data structure here. */ stack<int> a, b; MyQueue() { } /** Push element x to the back of queue. */ void push(int x) { a.push(x); } /** Removes the element from in front of queue and returns that element. */ int pop() { while (a.size() > 1) { b.push(a.top()); a.pop(); } int t = a.top(); a.pop(); while (b.size()) { a.push(b.top()); b.pop(); } return t; } /** Get the front element. */ int peek() { while (a.size() > 1) { b.push(a.top()); a.pop(); } int t = a.top(); while (b.size()) { a.push(b.top()); b.pop(); } return t; } /** Returns whether the queue is empty. */ bool empty() { return a.empty(); } }; /** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * bool param_4 = obj.empty(); */