思路:
用两个栈实现队列
pop操作,若out栈为空则先将in中元素push进out,再pop出out中元素
peek操作,直接调用pop,在将pop出元素push进out
class MyQueue {
public:
stack<int> in;
stack<int> out;
MyQueue() {
}
void push(int x) {
in.push(x);
}
int pop() {
int res;
if (out.empty()) {
while (in.size()) {
out.push(in.top());
in.pop();
}
}
res = out.top();
out.pop();
return res;
}
int peek() {
int res = pop();
out.push(res);
return res;
}
bool empty() {
return in.empty() && out.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();
*/
标签:int,res,pop,MyQueue,用栈,push,LeetCode,232,out
From: https://www.cnblogs.com/hjy94wo/p/16628894.html