将顺序栈,循环队列定义成模板类型:
#include <iostream>
using namespace std;
template <typename T,int Maxsize>
class seqstack
{
private:
T data[Maxsize];
int top;
public:
seqstack() //无参构造
{
top=-1;
cout<<"无参构造"<<endl;
}
seqstack(T d):data(d) //有参构造
{
top==-1;
cout<<"有参构造"<<endl;
}
bool isempty() //判空
{
return top==-1;
}
int size() //返回容纳的元素数
{
cout<<"栈中有"<<top+1<<"元素"<<endl;
return top+1;
}
void push(T key) //入栈
{
if(top==Maxsize-1)
{
cout<<"栈满"<<endl;
return;
}
data[++top]=key;
cout<<"入栈成功"<<endl;
return;
}
void pop() //出栈
{
if(top==-1)
{
cout<<"栈满"<<endl;
return;
}
data[top--];
cout<<"出栈成功"<<endl;
return;
}
};
template <typename T,int Maxsize>
class circularqueue
{
private:
T data[Maxsize];
int front;
int rear;
public:
circularqueue() //无参构造
{
front=rear;
cout<<"无参构造"<<endl;
}
circularqueue(T d):data(d) //有参构造
{
front=rear;
cout<<"有参构造"<<endl;
}
~circularqueue() //析构函数
{
cout<<"析构函数"<<endl;
}
int isfront() //输出第一个元素
{
cout<<"队列中第一个元素为:"<<data[front]<<endl;
return data[front];
}
int isback() //输出最后一个元素
{
cout<<"队列中最后一个元素为:"<<data[rear-1]<<endl;
return data[rear-1];
}
bool empty() //判空
{
return front==rear;
}
int size() //返回存储元素个数
{
cout<<"队列中存储了"<<(Maxsize-front+rear+1)%Maxsize<<"个元素"<<endl;
return (Maxsize-front+rear+1)%Maxsize;
}
void push(T key) //插入
{
if((rear+1)%Maxsize==front)
{
cout<<"队满"<<endl;
return;
}
data[rear]=key;
rear=(rear+1)%Maxsize;
cout<<"插入成功"<<endl;
return;
}
void pop() //删除
{
if(front==rear)
{
cout<<"队空"<<endl;
return;
}
front=(front+1)%Maxsize;
cout<<"删除成功"<<endl;
return;
}
};
int main()
{
seqstack<int,5> stack;
if(stack.isempty())
{
cout<<"栈空"<<endl;
}
stack.push(1);
stack.push(2);
stack.size();
cout<<endl;
circularqueue<char,10> queue;
if(queue.empty())
{
cout<<"队空"<<endl;
}
queue.push('a');
queue.push('b');
queue.size();
queue.isback();
queue.isfront();
return 0;
}
思维导图: