题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
// 网上看了些做法,不一定能编译通过的额! 还是自己动手写啊。。
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int out = NULL;
if (!stack2.empty())
{
out = stack2.top();
stack2.pop();// 这是个pop操作,所以需要pop这个转化栈
}
else
{
while (!stack1.empty())
{
stack2.push(stack1.top()); // 把存储栈的栈顶元素,放到装换栈的栈底
stack1.pop();
}
if (!stack2.empty())
{
out = stack2.top();
stack2.pop();
}
}
return out;
}
private:
stack<int> stack1;
stack<int> stack2;
};
本文介绍了一种使用两个栈来实现队列的方法,详细解释了如何通过栈的特性完成队列的Push和Pop操作,特别关注于int类型的元素处理。
943

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



