Problem: 232. 用栈实现队列
思路
现在有一个栈和队列,假如入栈的顺序和入队列的顺序相同。队列的大部分操作,如front(),和pop(),实际上就是每次对栈底的元素进行操作。由于栈只能对栈顶元素进行操作,我们需要使栈中元素的顺序和队列中元素的顺序相反。
解题方法
由于栈中的元素顺序和队列中元素的顺序相反,所以queue.front() == stack.top(), queue.empty() = stack.empty(), queue.pop() == stack.pop()。为了使栈中元素的顺序与队列中元素的顺序不同,所以我们在执行queue.push()的操作的时候需要在我们的逆序的栈的栈底加入新的元素,这里我使用了一个辅助栈来实现在栈底增加元素的需求。
复杂度
- 时间复杂度:
O ( 1 ) O(1) O(1)
- 空间复杂度:
O ( n ) O(n) O(n)
Code
/**
* 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();
*/
class MyQueue {
public:
stack<int> sta;
MyQueue() {
}
void push(int x) {
stack<int> tmp;
while(!sta.empty()) {
tmp.push(sta.top());
sta.pop();
}
tmp.push(x);
while(!tmp.empty()) {
sta.push(tmp.top());
tmp.pop();
}
}
int pop() {
int top = sta.top();
sta.pop();
return top;
}
int peek() {
return sta.top();
}
bool empty() {
return sta.empty();
}
};