题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
C++代码
//插入一个元素
void push(int node) {
stack1.push(node);//存储输入的元素
}
//弹出一个元素
int pop() {
//方法一:用stack2来接收stack1弹出的元素,形成一个和stack1相反的栈,再删除栈顶元素
//重新把stack2的元素弹出给stack1
#if 0
int que_value = 0;
if (stack1.empty())
return que_value;
while (!stack1.empty())
{
int value = stack1.top();//栈顶数据
stack1.pop();//出栈
stack2.push(value);
}
//stack2的栈顶 就是要删除的元素
que_value = stack2.top();
stack2.pop();//出栈
while (!stack2.empty())//还原stack1
{
int value = stack2.top();//栈顶元素
stack2.pop();//出栈
stack1.push(value);
}
return que_value;
#endif
#if 1//方法二:改进方法一,不需要在把stack2的元素push给stack1;因为要删除的表头元素一直是stack2的栈顶
int que_value = 0;
if (stack2.empty())//如果表2是空的,先把stack1的值都push给stack2,再弹出stack2的栈顶元素
{
if (stack1.empty())
return que_value;//空队列,不能完成pop操作
while (!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
}
que_value = stack2.top();
stack2.pop();
return que_value;
#endif
}