链式队列基本操作

来源:互联网 发布:三国无双7萝莉捏脸数据 编辑:程序博客网 时间:2024/04/30 02:01
#include<stdio.h>#include<stdlib.h>typedef int dataType;typedef struct  node{dataType data;struct node *next;}linklist;typedef struct{linklist *front;linklist *real;}linkqueue;void setnull(linkqueue *q)//置空{linklist *p=malloc(sizeof (linkqueue));q->front=q->real=p;q->front->next=NULL;}int  empty(linkqueue *q)//判断是否为空{return (q->front ==q->real);}void enqueue(linkqueue *q,dataType x)//入队{printf("入队:%d\n",x);linklist *p=malloc(sizeof(linkqueue));if(p==NULL){printf("error\n");exit(1);}p->data=x;p->next=NULL;if(empty(q)){q->front->next=p;q->real=p;}else{q->real->next=p;q->real=p;}return ;}dataType  dequeue(linkqueue *q)//出队{if(empty(q)){printf("queue is empty!\n");return 0;}else{linklist *p;p=q->front;q->front=q->front->next;free(p);printf("\n出队:%d\n",q->front->data);return (q->front->data);}}void clearqueue(linkqueue *q)//清除所有元素{printf("\n清除队列中*************\n\n");linklist *p;p=q->front;int count=1;while(p!=NULL){q->front=q->front->next;free(p);p=q->front;}q->real=NULL;printf("清除完成\n");}void printqueue(linkqueue *q)//打印所有元素{linklist *s;s=q->front->next;while(s!=NULL){printf("%d\t",s->data);s=s->next;}printf("\n\n");}dataType real(linkqueue *q)//打印队尾元素{if(empty(q)){printf("queue is empty!\n");}elsereturn (q->real->data);}dataType front(linkqueue *q)//打印队首元素{if(empty(q)){printf("queue is empty!\n");}elsereturn (q->front->next->data);}void main(){linkqueue p;setnull(&p);// 设为空printf("\n是否为空?\n%d\n\n",empty(&p));//判断是否为空enqueue(&p,2);//入队enqueue(&p,3);//入队enqueue(&p,4);//入队printf("\n是否为空?\n%d\n\n",empty(&p));//判断是否为空printf("\n打印队列:\n");printqueue(&p);printf("the front data:\n");printf("%d\n",front(&p));//打印frontprintf("the real data:\n");printf("%d\n",real(&p));//打印realdequeue(&p);//出队printf("the front data:\n");printf("%d\n",front(&p));//打印frontprintf("\n打印队列:\n");printqueue(&p);clearqueue(&p);printf("\n是否为空?\n%d\n",empty(&p));//判断是否为空}

运行结果:

是否为空?1入队:2入队:3入队:4是否为空?0打印队列:234the front data:2the real data:4出队:2the front data:3打印队列:34清除队列中*************清除完成是否为空?1


0 0
原创粉丝点击