题目地址:
https://leetcode.com/problems/implement-queue-using-stacks/
用栈来模拟队列。
可以用两个栈,一个模拟队列头,一个模拟队列尾。队尾的那个栈专门用来enqueue,队列头的那个栈专门用来dequeue。当dequeue的那个栈空了,就将enqueue里所有元素都倒进dequeue里去,这样顺序就再次反了一下,就变成FIFO了。代码如下:
class MyQueue {
public:
stack<int> stk, stk0;
MyQueue() {}
void push(int x) { stk.push(x); }
int pop() {
if (stk0.empty()) {
while (stk.size()) {
stk0.push(stk.top());
stk.pop();
}
}
int res = stk0.top();
stk0.pop();
return res;
}
int peek() {
if (stk0.empty()) {
while (stk.size()) {
stk0.push(stk.top());
stk.pop();
}
}
return stk0.top();
}
bool empty() { return stk.empty() && stk0.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();
*/
时间复杂度:push: O ( 1 ) O(1) O(1),pop和peek:均摊 O ( 1 ) O(1) O(1)。