用两个栈实现队列
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路
两个栈,st1和st2,push的时候往st1入栈,pop的时候,先把st1的元素倒到st2,再把st2的栈顶元素pop。
顺便
- 面试的时候被问到过这个,空间复杂度需要两倍的队列长度,时间复杂度push为O(1),pop为O(N)。
进一步,可以使用数组来实现队列,设定两个index,分别表示队列首尾,pop时候,取index1的元素,index1再自增1,push到时候,index2先自增1,再赋值。
这样pop、push的复杂度都是O(1),缺点是需要一块较大的连续空间。 - 再进一步,用链表来表示队列,设头指针和尾指针。pop、push时指针操作和数组中的index类似。
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
int res = stack2.top();
stack2.pop();
while(!stack2.empty()){
stack1.push(stack2.top());
stack2.pop();
}
return res;
}
private:
stack<int> stack1,stack2;
};
905

被折叠的 条评论
为什么被折叠?



