代码
#include<stdio.h>
#include<stdlib.h>
typedef struct Qnode{
int data; //存储元素
struct Qnode *next; //指向下一个结点的指针
}Qtype; //链队中数据结点的类型
typedef struct qptr{
Qtype *front;
Qtype *rear;
}LinkQueue; //链队结点类型
void InitQueue(LinkQueue *&lq) //初始化链队
{
lq=(LinkQueue *)malloc(sizeof(LinkQueue));
lq->front =lq->rear =NULL; //初始化指针指向空
}
void DestroyQueue(LinkQueue *&lq)
{
Qtype *pre=lq->front ,*p;
if(pre != NULL){
if(pre == lq->rear ){ //只有一个结点的情况
free(pre);
}else{
p=pre->next ;
while(p != NULL){
free(pre);
pre=p; p=p->next; //指针后移
}
free(pre);
}
}
free(lq); //释放链队结点
}
int EnQueue(LinkQueue *&lq, int x)
{
Qtype *s; //作为插入的新结点
s=(Qtype*)malloc(sizeof(Qtype)); //动态分配空间
s->data =x; s->next =NULL;
if(lq->front == NULL){ //队头指针为空,队列为空
lq->front =lq->rear =s; //此时,s即为队头又为队尾
}else{
lq->rear->next =s;
lq->rear =s;
}
return 1;
}
int DeQueue(LinkQueue *&lq, int &e)
{
Qtype *p;
if(lq->front == NULL){ //队列为空,返回0
return 0;
}
p=lq->front ;
e=p->data;
if(lq->front == lq->rear ){ //队列中只用一个元素,出队后将队列置空
lq->front =lq->rear =NULL;
}else{
lq->front =lq->front->next ; //存在两个或以上结点时,front指针后移,释放p
free(p);
return 1;
}
}
int GetHead(LinkQueue *lq, int &x)
{
if(lq->front == NULL){
return 0;
}
x=lq->front->data ;
return 1;
}
int QueueEmply(LinkQueue *lq)
{
if(lq->front == NULL) return 1; //确实为空
else return 0; //队不空返回0
}
int main()
{
LinkQueue *lq;
int e;
printf("初始化队列\n");
InitQueue(lq);
printf("队%s\n",(QueueEmply(lq) == 1? "空":"不空"));
printf("1进队\n"); EnQueue(lq,1);
printf("2进队\n"); EnQueue(lq,2);
printf("3进队\n"); EnQueue(lq,3);
printf("4进队\n"); EnQueue(lq,4);
printf("队%s\n",(QueueEmply(lq) == 1? "空":"不空"));
GetHead(lq,e);
printf("队头元素:%d\n",e);
while(!QueueEmply(lq)){
DeQueue(lq,e);
printf("%d ",e);
}
printf("\n");
DestroyQueue(lq);
return 0;
}