数据结构——循环队列
#include <iostream>
using namespace std;
#define MAXSIZE 9
typedef struct
{
int front;
int rear;
int data[MAXSIZE];
}CirQueue;
int count=0;
//初始化顺序队列
void init_queue(CirQueue * cq)
{
cq->front=cq->rear=0;
}
//判队列满
int full_queue(CirQueue * cq)
{
if(count==MAXSIZE)
return 1;
else
return 0;
}
//判队列空
int isempty_queue(CirQueue * cq)
{
if(count==0)
return 1;
else
return 0;
}
//入队列
int Push_queue(CirQueue * cq,int x)
{
if(full_queue(cq))
{
cout<<"队列已满,请删除后再添加!"<<endl;
return 0;
}
else
{
count++; //元素个数加1
cq->data[(cq->rear)%MAXSIZE]=x; //数据放在当前队尾指针指向的位置
cq->rear=(cq->rear+1)%MAXSIZE; //队尾指针向后移一位,放在最后一个元素的后面
return 1;
}
}
//显示队列
int display_queue(CirQueue * cq)
{
if(isempty_queue(cq)==1)
{
cout<<"is empty!"<<endl;
return 0;
}
int temp=cq->front;
int tempcount=count;
while(tempcount)
{
cout<<cq->data[temp]<<" ";
temp=(temp+1)%MAXSIZE;
tempcount--;
}
return 1;
}
//出队列
int Pop_queue(CirQueue * cq)
{
if(isempty_queue(cq)==1)
{
cout<<"is empty!"<<endl;
return 0;
}
cout<<cq->data[cq->front++]<<endl;
count--;
return 1;
}
//取队列顶元素
int gettop_queue(CirQueue * cq)
{
return cq->data[cq->front];
}
//查找元素
int search_queue(CirQueue * cq,int key)
{
int temp=cq->front;
int tempcount=count;
while(tempcount)
{
if(cq->data[temp]==key)
{
return 1;
}
temp=(temp+1)%MAXSIZE;
tempcount--;
}
return 0;
}
//置队列空
void clear_queue(CirQueue * cq)
{
cq->front=cq->rear=0;
count=0;
cout<<"置空成功!"<<endl;
}
int main()
{
CirQueue * cq;
cq=(CirQueue *) malloc(sizeof(CirQueue));
if(!cq)
{
printf("分配空间失败!\n");
return 0;
}
//初始化顺序队列
init_queue(cq);
//入队列
Push_queue(cq,15);
Push_queue(cq,23);
Push_queue(cq,54);
Push_queue(cq,67);
Push_queue(cq,32);
Push_queue(cq,24);
Push_queue(cq,38);
Push_queue(cq,47);
Push_queue(cq,95); //第九个元素
//显示队列
display_queue(cq);
cout<<endl;
Push_queue(cq,54); //第十个元素
//显示队列
display_queue(cq);
cout<<endl;
//出队列
cout<<"出队列"<<endl;
Pop_queue(cq);
Pop_queue(cq);
//显示队列
display_queue(cq);
cout<<endl;
//再入队列
Push_queue(cq,78);
Push_queue(cq,43);
//显示队列
display_queue(cq);
cout<<endl;
//取队列顶元素
cout<<"队列顶元素时: "<<gettop_queue(cq)<<endl;
//判队列空
if(isempty_queue(cq)==1)
cout<<"is empty!"<<endl;
else
cout<<"not empty!"<<endl;
//判队列满
full_queue(cq);
//查找元素
if(search_queue(cq,38))
cout<<"yes!find it."<<endl;
else
cout<<"is not exist."<<endl;
//置队列空
cout<<"置空线性队列? ";
clear_queue(cq);
display_queue(cq);
return 0;
}