两个栈实现队列的功能
来源:互联网 发布:知世和艾利欧 编辑:程序博客网 时间:2024/05/22 13:37
////**********两个栈实现队列的功能
其实就是用一个类包含两个栈,其中一个压栈,然后全部弹出到另一个栈,最后就是另一个栈弹出,从而达到先进先出
#include<iostream>
#include<stack>
using namespace std;
class myqueue
{
public:
void push(int t)
{
s1.push(t);
}
int front()
{
if(s2.empty())
{
if(s1.size()==0)cout<<"error";
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();//s1栈少了元素,而s2栈多了个元素
}
}
return s2.top();
}
void pop()
{
/*if(s2.empty())
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
if(!s2.empty())
s2.pop();
}
else*/
s2.pop();//这里很重要,因为每次其实都是从s2这个栈里面弹出来的
}
stack<int> s1;
stack<int> s2;
};
int main(void)
{
myqueue mq;
int i;
for(i=1;i<=10;i++)
mq.push(i*10);
for(i=0;i<10;i++)
{
cout<<mq.front()<<endl;
mq.pop();
}
return 0;
}
其实就是用一个类包含两个栈,其中一个压栈,然后全部弹出到另一个栈,最后就是另一个栈弹出,从而达到先进先出
#include<iostream>
#include<stack>
using namespace std;
class myqueue
{
public:
void push(int t)
{
s1.push(t);
}
int front()
{
if(s2.empty())
{
if(s1.size()==0)cout<<"error";
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();//s1栈少了元素,而s2栈多了个元素
}
}
return s2.top();
}
void pop()
{
/*if(s2.empty())
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
if(!s2.empty())
s2.pop();
}
else*/
s2.pop();//这里很重要,因为每次其实都是从s2这个栈里面弹出来的
}
stack<int> s1;
stack<int> s2;
};
int main(void)
{
myqueue mq;
int i;
for(i=1;i<=10;i++)
mq.push(i*10);
for(i=0;i<10;i++)
{
cout<<mq.front()<<endl;
mq.pop();
}
return 0;
}
0 0
- 两个队列实现一个栈的功能
- 两个栈实现一个队列的功能
- 两个栈实现队列的功能
- 两个栈实现队列的功能
- 两个栈实现队列的功能
- 用两个栈实现队列的功能
- 两个栈实现队列的功能
- 利用两个栈实现队列的功能
- 两个栈实现一个队列的功能
- 使用两个栈实现队列的功能
- 两个栈实现队列的功能
- 两个栈实现一个队列的功能
- 用两个栈实现一个队列的功能&&用两个队列实现一个栈的功能
- 用两个栈实现队列的功能和用两个队列实现栈的功能
- 两个栈实现队列功能
- 两个队列实现栈功能
- java 实现 两个栈实现一个队列的功能
- 用两个栈实现一个队列,用两个队列实现一个栈的功能
- 【问底】徐汉彬:大规模网站架构的缓存机制和几何分形学
- Ceph删除/添加故障OSD(ceph-deploy)
- .pch找不到的解决方法
- JVM 内存溢出 java.lang.OutOfMemoryError: PermGen space myeclipse10
- Android打包之Ant打包
- 两个栈实现队列的功能
- 从头到尾彻底解析Hash表算法
- Java的类名与文件名必须一致
- Android系统Recovery工作原理之使用update.zip升级过程分析(二)---update.zip差分包问题的解决
- 使用Gitbook制作电子书
- 又好又快,免费学习编程的9个地方
- 站内搜索 代码(Baidu,Google,Yahoo)
- 多个有序数列中查找第k小值
- linux格式化