C语言单链队列的表示与实现实例详解
1.概述:
C语言的队列(queue),是指先进先出(FIFO,First-In-First-Out)的线性表。在具体应用中通常用链表或者数组来实现。队列只允许在后端(称为rear)进行插入操作,在前端(称为front)进行删除操作。
而单链队列使用链表作为基本数据结果,因此不存在伪溢出的问题,队列长度也没有限制。但插入和读取的时间代价会比较高
2.实例代码:
/*单链队列——队列的链式存储结构*/ typedefstructQNode { QElemTypedata; structQNode*next; }QNode,*QueuePtr; typedefstruct { QueuePtrfront,rear;/*队头、队尾指针*/ }LinkQueue; /*链队列的基本操作(9个)*/ voidInitQueue(LinkQueue*Q) {/*构造一个空队列Q*/ Q->front=Q->rear=malloc(sizeof(QNode)); if(!Q->front) exit(OVERFLOW); Q->front->next=NULL; } voidDestroyQueue(LinkQueue*Q) {/*销毁队列Q(无论空否均可)*/ while(Q->front) { Q->rear=Q->front->next; free(Q->front); Q->front=Q->rear; } } voidClearQueue(LinkQueue*Q) {/*将Q清为空队列*/ QueuePtrp,q; Q->rear=Q->front; p=Q->front->next; Q->front->next=NULL; while(p) { q=p; p=p->next; free(q); } } StatusQueueEmpty(LinkQueueQ) {/*若Q为空队列,则返回TRUE,否则返回FALSE*/ if(Q.front->next==NULL) returnTRUE; else returnFALSE; } intQueueLength(LinkQueueQ) {/*求队列的长度*/ inti=0; QueuePtrp; p=Q.front; while(Q.rear!=p) { i++; p=p->next; } returni; } StatusGetHead_Q(LinkQueueQ,QElemType*e) {/*若队列不空,则用e返回Q的队头元素,并返回OK,否则返回ERROR*/ QueuePtrp; if(Q.front==Q.rear) returnERROR; p=Q.front->next; *e=p->data; returnOK; } voidEnQueue(LinkQueue*Q,QElemTypee) {/*插入元素e为Q的新的队尾元素*/ QueuePtrp=(QueuePtr)malloc(sizeof(QNode)); if(!p)/*存储分配失败*/ exit(OVERFLOW); p->data=e; p->next=NULL; Q->rear->next=p; Q->rear=p; } StatusDeQueue(LinkQueue*Q,QElemType*e) {/*若队列不空,删除Q的队头元素,用e返回其值,并返回OK,否则返回ERROR*/ QueuePtrp; if(Q->front==Q->rear) returnERROR; p=Q->front;/*指向头结点*/ *e=p->data; Q->front=p->next;/*摘下头节点*/ if(Q->rear==p) Q->rear=Q->front; free(p); returnOK; } voidQueueTraverse(LinkQueueQ,void(*vi)(QElemType)) {/*从队头到队尾依次对队列Q中每个元素调用函数vi()*/ QueuePtrp; p=Q.front->next; while(p) { vi(p->data); p=p->next; } printf("\n"); }