队列用链表实现(建立,插入新元素,删除元素,读取元素,全部删除,全部读出,判断是否为空,清空)
下午把队列的各种操作用链表实现了一下,建立,插入元素,删除元素,读取元素,全部删除,全部读出,判断是否为空,清空,源代码调试已经通过,运行结果如下图所示:
#include "iostream"
using namespace std;
typedef struct student
{
int data;
struct student * next;
}node;//定义结构体节点
typedef struct linkqueue
{
node * first;
node * rear;
}queue;//定义队列结构,首指针和尾指针
/*******************************
函数名:void initqueue(queue *HQ)
功能:初始化 把队首和队尾指针置空
********************************/
void initqueue(queue *HQ)
{
HQ->first=HQ->rear=NULL;
}
/**************************************
函数名:queue *insert(queue *HQ,int x)
功能:向队列中添加一个新元素,在尾节点之后
***************************************/
queue *insert(queue *HQ,int x)
{
node * s;
s=new node;
s->data=x;
s->next=NULL;
if (HQ->rear==NULL)
{
HQ->first=s;
HQ->rear=s;
}
else
{
HQ->rear->next=s;
HQ->rear=s;
}
return HQ;
}
/******************************
函数名:int delqueue(queue *HQ)
功能:从队列中删除一个元素*
*******************************/
int delqueue(queue *HQ)
{
node *p;
int temp;
/*若链队为空则停止运行*/
if(HQ->first==NULL)
{
printf("队列为空,无法删除! ");
exit(1);
}
temp=HQ->first->data;
/*暂存队首元素以便返回*/
p=HQ->first;
/*暂存队首指针以便回收队尾结点*/
HQ->first=p->next; /*使队首指针指向下一个结点*/
/*若删除后链队为空,则需同时使队尾指针为空*/
if(HQ->first==NULL)
{
HQ->rear=NULL;
}
free(p); /*回收原队首结点*/
return temp; /*返回被删除的队首元素值*/
}
/*******************************
函数名:int readqueue(queue *HQ)
功能:读取队首元素*
********************************/
int readqueue(queue *HQ)
{ /*若链队为空则停止运行*/
if(HQ->first==NULL)
{
cout<<"队列为空,无法删除! ";
exit(1);
}
return HQ->first->data; /*返回队首元素*/
}
/*************************************************
函数名:int emptyqueue(queue *HQ)
功能:检查链队是否为空,若为空则返回1,否则返回0
************************************************/
int emptyqueue(queue *HQ)
{
/*判断队首或队尾任一个指针是否为空即可*/
if(HQ->first==NULL)
{
return 1;
}
else
{
return 0;
}
}
/***********************************
函数名:void clearqueue(queue *HQ)
功能:清除链队中的所有元素*
***********************************/
void clearqueue(queue *HQ)
{
node *p=HQ->first; /*队首指针赋给p*/
/*依次删除队列中的每一个结点,最后使队首指针为空*/
while(p!=NULL)
{
HQ->first=HQ->first->next;
free(p);
p=HQ->first;
}
/*循环结束后队首指针已经为空*/
HQ->rear=NULL; /*置队尾指针为空*/
}
/*******************************
函数名:void readall(queue *HQ)
功能:输出链队中的所有元素
*********************************/
void readall(queue *HQ)
{
node *p=HQ->first;
while (p!=NULL)
{
cout<<p->data<<endl;
p=p->next;
}
}
void main()
{
queue q;
int a[5]={1,2,3,4,5};
int i;
initqueue(&q);
for(i=0;i<5;i++)
{
insert(&q,a[i]);
}//队列中插入数据 1,2,3,4,5
cout<<endl<<"读取队列中全部的数据:\n";
readall(&q);//读取队列中全部数据
insert(&q,60);//插入一个数据
cout<<"读取的队首节点:"<<readqueue(&q)<<endl;//读取队首元素
cout<<endl;
while(!emptyqueue(&q))
{
cout<<"删除的节点:"<<delqueue(&q)<<endl;;
cout<<"剩下的节点"<<endl;
readall(&q);
}
clearqueue(&q);
}
运行结果:

浙公网安备 33010602011771号