剑指Offer编程练习005——用两个栈实现队列
2018-03-25 18:52
295 查看
题目:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
class Solution
{
public:
void push(int node) {
}
int pop() {
}
private:
stack<int> stack1;
stack<int> stack2;
};
思路:
入队:将元素进栈A
出队:判断栈B是否为空,如果为空,则将栈A中所有元素pop,并push进栈B,栈B出栈;如果栈B不为空,栈B直接出栈。#include<stack>
using namespace std;
class Solution
{
public:
void push(int node) //入队的过程就是栈1压栈的过程
{
stack1.push(node);
}
int pop()
{
int a;//用来储存出队的元素
if (stack2.empty())//如果栈2是空的,
{
while (!stack1.empty())//栈1中有元素就把所有元素弹出然后压入栈2中
{
a = stack1.top();
stack2.push(a);
stack1.pop();
}
}
a = stack2.top();//取出栈2的栈顶元素放入a中
stack2.pop();//弹出栈2的栈顶元素
return a;
}
private:
stack<int> stack1;
stack<int> stack2;
};
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
class Solution
{
public:
void push(int node) {
}
int pop() {
}
private:
stack<int> stack1;
stack<int> stack2;
};
思路:
入队:将元素进栈A
出队:判断栈B是否为空,如果为空,则将栈A中所有元素pop,并push进栈B,栈B出栈;如果栈B不为空,栈B直接出栈。#include<stack>
using namespace std;
class Solution
{
public:
void push(int node) //入队的过程就是栈1压栈的过程
{
stack1.push(node);
}
int pop()
{
int a;//用来储存出队的元素
if (stack2.empty())//如果栈2是空的,
{
while (!stack1.empty())//栈1中有元素就把所有元素弹出然后压入栈2中
{
a = stack1.top();
stack2.push(a);
stack1.pop();
}
}
a = stack2.top();//取出栈2的栈顶元素放入a中
stack2.pop();//弹出栈2的栈顶元素
return a;
}
private:
stack<int> stack1;
stack<int> stack2;
};
相关文章推荐
- 编程练习——用两个栈实现一个队列
- 牛客《剑指Offer》 用两个栈实现队列
- 《剑指Offer》用两个栈来实现队列
- 剑指Offer系列---(9)用两个栈实现队列和用两个队列实现栈
- 【练习笔记】剑指offer-面试题7 :用两个栈实现队列
- 剑指offer面试题之用两个栈实现队列
- [每日练习]编程实现两个正整数的除法
- 用两个栈实现队列(剑指offer)
- 《剑指offer》---两个队列来实现栈 和 O(n)时间内对年龄排序
- 剑指offer系列-用两个栈实现队列
- 剑指offer 编程题(5):两个栈实现队列,两个队列实现栈
- 剑指offer-面试题7-用两个栈实现队列
- 《剑指offer》(面试题7):用两个栈实现队列
- C++笔试题(剑指offer 面试题7 两个栈实现队列)
- 剑指offer 面试题7 两个栈实现队列
- 牛客网-《剑指offer》-用两个栈实现队列
- 剑指offer-用两个栈实现队列
- 《剑指Offer》用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。java
- 《剑指offer》-用两个栈实现队列
- 《剑指Offer》面试题:用两个栈来实现一个队列