由两个栈实现一个队列
来源:互联网 发布:为什么淘宝开店开不了 编辑:程序博客网 时间:2024/06/02 03:18
#include<iostream>
#include<exception>
#include<stack>//使用栈
using namespace std;
template<typename T> class queue{//模板类的定义
public:
queue(void);
~queue(void);
void appendtail(const T& num);//成员函数一般是共有的
T deletehead();
private:
stack<T> stack1;//成员变量私有化
stack<T> stack2;
};
template<typename T> queue<T>::queue(void)//模板类函数的定义
{
}
template<typename T> queue<T>::~queue(void){
}
template<typename T> void queue<T>::appendtail(const T& num)
{
stack1.push(num);
}
template<typename T> T queue<T>::deletehead()
{
if (stack2.size()>0)
{
T head = stack2.top();
stack2.pop();
return head;
}
else if (stack2.size() <= 0)
{
if (stack1.size() > 0)
{
while (stack1.size() > 0)
{
T data = stack1.top();
stack1.pop();//栈的使用
stack2.push(data);
}
T head = stack2.top();
stack2.pop();
return head;
}
}
else
throw exception("empty!");
}
int main()
{
queue<char> qe;//由模板类定义对象
qe.appendtail('a');
qe.appendtail('b');
qe.appendtail('c');
qe.appendtail('d');
char head;
cout << (head = qe.deletehead()) << endl;
cout << (head = qe.deletehead()) << endl;
qe.appendtail('e');
cout << (head = qe.deletehead()) << endl;
cout << (head = qe.deletehead()) << endl;
cout << (head = qe.deletehead()) << endl;
}
#include<exception>
#include<stack>//使用栈
using namespace std;
template<typename T> class queue{//模板类的定义
public:
queue(void);
~queue(void);
void appendtail(const T& num);//成员函数一般是共有的
T deletehead();
private:
stack<T> stack1;//成员变量私有化
stack<T> stack2;
};
template<typename T> queue<T>::queue(void)//模板类函数的定义
{
}
template<typename T> queue<T>::~queue(void){
}
template<typename T> void queue<T>::appendtail(const T& num)
{
stack1.push(num);
}
template<typename T> T queue<T>::deletehead()
{
if (stack2.size()>0)
{
T head = stack2.top();
stack2.pop();
return head;
}
else if (stack2.size() <= 0)
{
if (stack1.size() > 0)
{
while (stack1.size() > 0)
{
T data = stack1.top();
stack1.pop();//栈的使用
stack2.push(data);
}
T head = stack2.top();
stack2.pop();
return head;
}
}
else
throw exception("empty!");
}
int main()
{
queue<char> qe;//由模板类定义对象
qe.appendtail('a');
qe.appendtail('b');
qe.appendtail('c');
qe.appendtail('d');
char head;
cout << (head = qe.deletehead()) << endl;
cout << (head = qe.deletehead()) << endl;
qe.appendtail('e');
cout << (head = qe.deletehead()) << endl;
cout << (head = qe.deletehead()) << endl;
cout << (head = qe.deletehead()) << endl;
}
阅读全文
0 0
- 由两个栈实现一个队列
- 由两个栈实现一个队列
- 由两个栈实现队列
- 两个队列实现一个栈&两个栈实现一个队列
- 两个栈实现一个队列-----两个队列实现一个栈
- 两个栈实现一个队列&&两个队列实现一个栈
- 两个栈实现一个队列 && 两个队列实现一个栈
- 两个栈实现一个队列,两个队列实现一个栈
- 两个栈实现一个队列/两个队列实现一个栈
- 两个栈实现一个队列&两个队列实现一个栈
- 两个队列实现一个栈&两个栈实现一个队列
- 两个队列实现一个栈 / 两个栈实现一个队列
- 两个栈实现一个队列,两个队列实现一个栈
- 两个栈实现一个队列&两个队列实现一个栈
- 两个栈实现一个队列&&两个队列实现一个栈
- 两个栈实现一个队列&两个队列实现一个栈
- 两个栈实现一个队列/两个队列实现一个栈
- 两个栈实现一个队列
- 美国总统就职演说词汇分布图
- 前端入门
- 排序--归并排序
- codeforces 841A Generous Kefa
- JS 实现Base64编码与解码实例详解
- 由两个栈实现一个队列
- Friend-Graph(数学,思维)
- idea热部署
- 一套实用的渗透测试岗位面试题,你会吗?
- 非诚勿扰
- 用两个栈模拟一个队列
- jsp内置对象
- stm32 FSMC-TFTLCD显示
- Snow的追寻