题目
两个栈实现队列的pop和push
考察点
- 队列与栈的概念
解题思路
stack1表示入队列,stack2表示出队列。
完整代码
/*05_stacktoqueue*/
#include<iostream>
#include<stack>
using namespace std;
class Solution
{
public:
void push(int node)
{
stack1.push(node);
}
int pop()
{
int value;
if (stack2.empty())
{
while (!stack1.empty())
{
value = stack1.top();
stack2.push(value);
stack1.pop();
}
}
value = stack2.top();
stack2.pop();
return value;//返回值
}
private:
stack<int> stack1;
stack<int> stack2;
};
int main()
{
Solution s;
for (int i = 0; i < 10; i++)
{
s.push(i);
}
for (int i = 0; i < 10; i++)
{
cout << s.pop();
}
cout << endl;
return 0;
}
编程遇见问题
- 栈的
top
pop
的使用
刚开始企图直接用value=stack1.pop()
一步完成stack1的出栈和获取stack1的栈顶元素,但总报错。后改为:
value = stack1.top();
stack2.push(value);
stack1.pop();
原因:top()
是有返回值,而pop()
没有返回值,只负责弹出。所以,要先取stack1的栈顶元素,再压入stack2,最后弹出stack1的栈顶元素。再后面主函数中,打印时也是要注意函数有无返回值。
if
与while
的区别
刚开始,我使用if
作为stack1是否为空的判断,编译失败后,改为while
成功
原因:if
是一个判断语句,只判断一次,while
是个循环语句,会执行很多次直至条件不满足。