1. 题目来源
链接:232. 用栈实现队列
2. 题目解析
栈实现队列这个问题较为常见,难度较低,两个栈来回倒一次就行了,主要是看看如何简洁的进行代码实现。
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( 1 ) O(1) O(1)
class MyQueue {
public:
stack<int> a, b;
void in2out(stack<int> &a, stack<int> &b) {
while (a.size()) b.push(a.top()), a.pop();
}
MyQueue() {
}
void push(int x) {
if (!a.size()) in2out(b, a);
a.push(x);
}
int pop() {
if (!b.size()) in2out(a, b);
int x = b.top();
b.pop();
return x;
}
int peek() {
if (!b.size()) in2out(a, b);
return b.top();
}
bool empty() {
return !a.size() && !b.size();
}
};
/**
* 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();
*/