使用模板类,实现用两个栈模拟队列的功能
2013-07-22 11:29
267 查看
// 使用模板类,实现用两个栈模拟队列的功能
#include <stdlib.h>
#include <iostream>
#include <stack>
using namespace std;
template<class T>
struct MyQueue
{
void push(T &t)
{
s1.push(t);
}
T front()
{
if(s2.empty())
{
if(s1.size()== 0 ) throw;
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
return s2.top();
}
void pop()
{
if(s2.empty())
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
if(!s2.empty())
{
s2.pop();
}
}
stack<T> s1;
stack<T> s2;
};
void main()
{
MyQueue<int> mq;
int i;
for(i=0; i<10; i++)
mq.push(i);
for(i=0; i<10; i++)
{
cout<<mq.front()<<endl;
mq.pop();
}
system("pause");
}
程序来自<程序员面试宝典3>178页
#include <stdlib.h>
#include <iostream>
#include <stack>
using namespace std;
template<class T>
struct MyQueue
{
void push(T &t)
{
s1.push(t);
}
T front()
{
if(s2.empty())
{
if(s1.size()== 0 ) throw;
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
return s2.top();
}
void pop()
{
if(s2.empty())
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
if(!s2.empty())
{
s2.pop();
}
}
stack<T> s1;
stack<T> s2;
};
void main()
{
MyQueue<int> mq;
int i;
for(i=0; i<10; i++)
mq.push(i);
for(i=0; i<10; i++)
{
cout<<mq.front()<<endl;
mq.pop();
}
system("pause");
}
程序来自<程序员面试宝典3>178页
相关文章推荐
- 使用两个栈实现队列的功能
- 面试题7_使用两个栈实现一个队列的功能
- PHP使用两个栈实现队列功能的方法
- 自定义栈的实现及使用两个栈模拟队列
- 使用两个堆栈实现队列功能
- 使用堆栈(Stack)来模拟队列(FIFO)功能,要求数据必须存储在堆栈内部.需要实现enqueue(入栈),dequeue(出栈),isEmpty(判空)三个功能,并给出单元测试.
- java使用两个栈模拟队列的实现
- 【干货】容器适配器实现两个栈模拟队列
- 用两个堆栈实现一个列表的功能(主要是入队列和出队列)
- 使用两个队列实现一个栈
- PHP使用Curl实现模拟登录及抓取数据功能示例
- 使用两个栈实现一个队列+使用两个队列实现一个栈
- 使用两个栈来实现队列
- Java用两个队列实现一个栈的功能
- 用两个栈实现一个队列的功能,请用C++实现它
- 两个栈实现队列的功能
- 使用两个队列实现一个栈
- 利用两个栈实现队列的功能
- java 实现 两个栈实现一个队列的功能
- 使用两个Stack类(JDK容器类库中的Stack类)实现一个队列类MyQueue,提供队列的入队列和出队列操作:enQueue和deQueue