题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路
《剑指offer》P59
入队的元素进入stack1,出队的元素从stack2中获取:
- 入栈时:直接push进stack1中即可;
- 出栈时考虑两种情况:
- stack2为空时,需要将stack1中的元素依次弹出并压入stack2中,再从stack2中取即可;
- stack2不为空时,直接从stack2中取元素(因为stack2中元素已倒序)。
code
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if (stack2.empty()) {
while (!stack1.empty()) {
int tmp = stack1.top();
stack2.push(tmp);
stack1.pop();
}
}
int res = stack2.top();
stack2.pop();
return res;
}
private:
stack<int> stack1;
stack<int> stack2;
};
拓展
用两个队列q1和q2实现一个栈的push和pop操作,思路如下:
- push:如果q1和q2都为空,则放入q1中;如果有一个不为空,则push进非空的队列中。
- pop:在有元素的情况下,一定是q1和q2一个为空,另一个非空。将非空队列中的元素,除了最后一个,其他全都移动到另一个队列,保存最后一个元素的值,然后pop。返回该元素。
# 用两个队列实现一个栈
class Solution
{
public:
void push(int node)
{
if (!queue2.empty())
queue2.push(node);
else
queue1.push(node);
}
int pop()
{
if (queue2.empty())
{
while (queue1.size() > 1)
{
int tmp = queue1.front();
queue2.push(tmp);
queue1.pop();
}
int res = queue1.front();
queue1.pop();
return res;
}
else
{
while (queue2.size() > 1)
{
int tmp = queue2.front();
queue1.push(tmp);
queue2.pop();
}
int res = queue2.front();
queue2.pop();
return res;
}
}
private:
queue<int> queue1;
queue<int> queue2;
};
550




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



