222
class MyQueue {
private:
stack<int> stackIn,stackOut;
public:
MyQueue() {
}
void push(int x) {
stackIn.push(x);
}
int pop() {
if(stackOut.empty()){
while(!stackIn.empty()){
stackOut.push(stackIn.top());
stackIn.pop();
}
}
int res = stackOut.top();
stackOut.pop();
return res;
}
int peek() {
int res = this->pop();
stackOut.push(res);
return res;
}
bool empty() {
return stackIn.empty() && stackOut.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> q1;
queue<int> q2;
public:
MyStack() {
}
void push(int x) {
q1.push(x);
}
int pop() {
// 当q2为空时,将q1中的元素除了最后一个外都转移到q2
if (q2.empty()) {
while (q1.size() > 1) {
q2.push(q1.front());
q1.pop();
}
}
// q1的最后一个元素即为栈顶元素,弹出并返回
int topElement = q1.front();
q1.pop();
// 交换q1和q2的角色,确保下一次pop操作可以快速执行
swap(q1, q2);
return topElement;
}
int top() {
return q1.back();
}
bool empty() {
return q1.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();
*/