用两个栈实现一个队列功能
2015-11-05 01:46
549 查看
#include<iostream>
#include<stack>
using namespace
std;
/*使用两个堆栈实现队列
s1:实现入队,s2:实现出队
首先,将数据存放在栈s1中,然后将数据push进s2中,再将s2中的数据pop
出队列:
(1)如果栈B不为空,直接弹出栈B的数据
(2)如果栈B为空,则依次弹出栈A的数据,放入栈B中,再弹出栈B的数据
*/
template<class T>
struct Queue
{
stack<T> s1;
stack<T> s2;
//s1入栈一个元素
void push(T &t)
{
s1.push(t);
}
//取出s2栈顶的元素,并移除。
T front()
{
if(s2.empty())
{
if(s1.size()==0)
throw;
while(!s1.empty())
{
s2.push(s1.top());
s1.pop(); //取出不要漏掉移除栈顶元素
}
}
int value =
s2.top();
s2.pop();
return value;
}
//把s1的内容倒入s2中
void pop()
{
if(s2.empty())
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
}
};
#include<stack>
using namespace
std;
/*使用两个堆栈实现队列
s1:实现入队,s2:实现出队
首先,将数据存放在栈s1中,然后将数据push进s2中,再将s2中的数据pop
出队列:
(1)如果栈B不为空,直接弹出栈B的数据
(2)如果栈B为空,则依次弹出栈A的数据,放入栈B中,再弹出栈B的数据
*/
template<class T>
struct Queue
{
stack<T> s1;
stack<T> s2;
//s1入栈一个元素
void push(T &t)
{
s1.push(t);
}
//取出s2栈顶的元素,并移除。
T front()
{
if(s2.empty())
{
if(s1.size()==0)
throw;
while(!s1.empty())
{
s2.push(s1.top());
s1.pop(); //取出不要漏掉移除栈顶元素
}
}
int value =
s2.top();
s2.pop();
return value;
}
//把s1的内容倒入s2中
void pop()
{
if(s2.empty())
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
}
};
相关文章推荐
- CVG Talks on CHIST-ERA 2015
- 单词搜索
- DP:Space Elevator(POJ 2392)
- LeetCode Integer to English Words
- composer 报错笔记
- 五分钟理解一致性哈希算法(consistent hashing)
- 虚拟机安装VBoxAdditions增强功能
- Unity的实时绘制与坐标转换总结
- 2013年华为c语言上机试题3
- 关于linux Centos 7一个网卡配置多个IP的方法
- [Lintcode] Insert Node in a Binary Search Tree
- scau_热身游戏(高精度)
- Session.load()和get()方法区别
- Django url 标签和reverse()函数的使用(转)
- OpenGL ES 3.0之顶点缓冲
- jquery easyui
- C++设计模式-Adapter适配器模式
- 回射客户端服务器中僵尸进程的处理( the solution of zombie process in the echo client && server )
- lazyload隐藏元素不生效处理方法
- 6回归分析