class MyQueue {
private:stack<int> inStack, outStack;void in2out(){while(!inStack.empty()){outStack.push(inStack.top());inStack.pop();}}public:MyQueue() {}void push(int x) {inStack.push(x);}int pop() {if(outStack.empty()){in2out();}int x = outStack.top();outStack.pop();return x;}int peek() {if(outStack.empty()){in2out();}return outStack.top();}bool empty() {return inStack.empty() && outStack.empty();}
};/*** Your MyQueue object will be instantiated and called as such:* MyQueue* obj = new MyQueue();* obj->push(x);* int param_2 = obj->pop();* int param_3 = obj->peek();* bool param_4 = obj->empty();*/
225. 用队列实现栈
class MyStack {private:queue<int> queue1, queue2;
public:MyStack() {}void push(int x) {queue2.push(x);while(!queue1.empty()){queue2.push(queue1.front());queue1.pop();}swap(queue1, queue2);}int pop() {int r = queue1.front();queue1.pop();return r;}int top() {int r = queue1.front();return r;}bool empty() {return queue1.empty();}
};/*** Your MyStack object will be instantiated and called as such:* MyStack* obj = new MyStack();* obj->push(x);* int param_2 = obj->pop();* int param_3 = obj->top();* bool param_4 = obj->empty();*/