将之前定义的栈类和队列类都实现成模板类
栈:
#include <iostream>
using namespace std;
template<typename T>
class zn
{
private:
T *num;
int top;
int size;
public:
//有参构造函数
zn(int a):top(-1),size(a){
num=new T[size];
}
//析构函数
~zn()
{
delete []num;
num=NULL;
}
//判空
bool myemp()
{
if(top==-1)
{
return true;
}
return false;
}
//判满
bool myfull()
{
if(top==size)
{
return true;
}
return false;
}
//入栈
int myinput()
{
if(myfull())
{
cout<<"入栈失败"<<endl;
return 0;
}
top+=1;
cin>>num[top];
cout<<"入栈成功"<<endl;
return 1;
}
//出栈
int myoutput()
{
if(myemp())
{
cout<<"出栈失败"<<endl;
return 0;
}
top-=1;
cout<<"出栈成功"<<endl;
return 1;
}
//获取栈顶元素
int gettop()
{
if(myemp())
{
cout<<"获取失败"<<endl;
return 0;
}
cout<<"栈顶元素为:"<<num[top]<<endl;
return 1;
}
//清空栈
int myclear()
{
if(myemp())
{
return 0;
}
this->top=-1;
cout<<"清空成功"<<endl;
return 1;
}
//求栈的大小
void mysize()
{
cout<<"栈的大小为:"<<top+1<<endl;
}
void show()
{
for(int i=0;i<=(top);i++)
{
cout<<num[i]<<" ";
}
cout<<endl;
}
};
int main()
{
zn<string> a1(5);
a1.myinput();
a1.myinput();
a1.myinput();
a1.myinput();
a1.gettop();
a1.myoutput();
a1.show();
a1.myclear();
a1.gettop();
a1.mysize();
return 0;
}
队列
#include <iostream>
using namespace std;
template<typename T>
class dl
{
private:
T *num;
int tail=0; //队尾
int head=0; //队头
public:
//无参构造
dl():num(new T[10]){}
//拷贝构造
dl(const dl &other):num(new int[10]),tail(other.tail),head(other.head)
{
int i=other.head;
do
{
num[i]=other.num[i];
i=(i+1)%10;
}while(i!=other.tail);
}
//析构函数
~dl(){
delete []num;
num=NULL;
}
//入队
void input()
{
if(myfull())
{
cout<<"队列满啦"<<endl;
}else
{
cin>>num[tail];
tail=(tail+1)%10;
}
}
//出队
void output()
{
if(myemp())
{
cout<<"队列无元素"<<endl;
}else
{
cout<<num[head]<<"出队成功"<<endl;;
head=(head+1)%10;
}
}
//清空队列
void clear()
{
head=tail;
cout<<"清空成功"<<endl;
}
//判空
bool myemp()
{
if(head==tail)
{
return true;
}
return false;
}
//判满
bool myfull()
{
if((tail+1)%10==head)
{
return true;
}
return false;
}
//求队列的大小
void mysize()
{
cout<<"队列大小为"<<(tail-head+10)%10<<endl;
}
void show()
{
cout<<"队列元素为:";
int i=head;
do
{
cout<<num[i]<<" ";
i=(i+1)%10;
}while(i!=tail);
cout<<endl;
}
};
int main()
{
dl<double> s1;
s1.input();
s1.show();
return 0;
}