#include <iostream>
#define SIZE 4
using namespace std;
//顺序栈 模板类定义
template <typename T>
class Stack
{
private:
T* stack;//栈的数组指针
int top;//栈顶
int maxsize;//栈的最大容量
public:
Stack()//构造函数,初始化栈的大小
{
stack=new T[SIZE];
top=-1;
maxsize=SIZE;
}
//析构函数,释放动态内存
~Stack(){delete [] stack;cout<<"stack 析构函数"<<endl;}
//判空
bool Empty()const
{
return(-1==top);
}
//判满
bool Full()const
{
return(SIZE-1==top);
}
//入栈
void push(const T&other)
{
if(Full())
{
cout<<"栈满...."<<endl;
}
stack[++top]=other;
}
//出栈
T pop()
{
if(Empty())
{
cout<<"栈空...."<<endl;
}
return stack[top--];
}
//栈的遍历
void show()
{
for(int i=0;i<SIZE;i++){
cout<<" "<<stack[i];}
cout<<endl;
}
};
//**************************************************
//循环队列模板类定义
template <typename T>
class Queue
{
private:
T*queue;//队列数组指针
int front;//队列头
int rear;//队列尾
int count;//队列中的成员数量
public:
Queue()//构造函数
{
queue=new T[SIZE];
front=0;
rear=0;
count=0;
}
//析构函数,释放动态内存
~Queue(){delete []queue;cout<<"queue 析构函数"<<endl;}
//判断是否队列存在
bool Exit()
{
if(queue!=nullptr)
{
cout<<"队列存在"<<endl;
return true;
}
}
//判空
bool Empty()const
{
return count == 0 || front == rear;
}
//判满
bool Full()const
{
return front == (rear + 1) % SIZE;
}
//删除
void Dequeue()
{
if(Empty())//结果为真则提示队列已空
cout<<"队列是空的没东西删"<<endl;
cout<<"出队的元素为:"<<queue[front]<<endl;
front=(front+1)%SIZE;//更新头部位置和count
count--;
}
//添加
void Enqueue(const T&other)
{
if(Full())//结果为真则提示队列已满
cout<<"队列已满,没法插入"<<endl;
queue[rear]=other;//将元素添加到队列尾部
rear=(rear+1)%SIZE;//更新尾部位置和count
count++;
}
//循环队列的遍历及数目
void show()
{
if(Empty())
cout<<"空的....0"<<endl;
else
for(int i=front;i!=rear;i=(i+1)%SIZE)
{
cout<<queue[i]<<" ";
}
cout<<endl<<"元素数量为"<<count<<endl;
}
};
int main()
{//测试顺序栈
Stack<int>s;
s.push(1);
s.push(3);
s.push(6);
s.push(4);
//判空
cout<<s.Empty()<<endl;
//判满
cout<<s.Full()<<endl;
//出栈
cout<<"出栈成员为:"<<s.pop()<<endl;
//入栈
s.push(6);
//遍历
s.show();
//*******************循环队列的测试
Queue<int>q;
q.Exit();//循环队列是否存在
q.Enqueue(11);
q.Enqueue(22);
q.Enqueue(33);
//判满
cout<<q.Full()<<endl;
//判空
cout<<q.Empty()<<endl;
//出队
q.Dequeue();
//入队
q.Enqueue(66);
//遍历
q.show();
return 0;
}
12-09
230