原题链接:https://leetcode-cn.com/problems/implement-queue-using-stacks/
代码如下:
//用栈实现队列。
class MyQueue {
public:
stack<int> left;
stack<int> right;
/*将元素x推到队列的后面。*/
void push(int x) {
right.push(x);
}
/*从队列前面移除元素并返回该元素。*/
int pop() {
if (left.empty()) {
int size = right.size();
for (int i = 0; i < size; i++) {
int d = right.top();
right.pop();
left.push(d);
}
}
int v = left.top();
left.pop();
return v;
}
/*获取front元素。*/
int peek() {
if (left.empty()) {
int size = right.size();
for (int i = 0; i < size; i++) {
int d = right.top();
right.pop();
left.push(d);
}
}
int v = left.top();
return v;
}
/*返回队列是否为空。*/
bool empty() {
return left.empty() && right.empty();
}
};