/* 本程序是链队的基本用法 创建空队、 进队、 出队、 判空、 清空、 获取队列长度、 销毁队 */ /* main.c */ #include<stdio.h> #include"linkqueue.h" int main() { linkqueue lq = CreateQueue(); EnQueue(lq,100); EnQueue(lq,200); EnQueue(lq,300); // ClearQueue(lq); // 清空队列 //GetLenth(lq); // 队列长度 while(FALSE == EmptyQueue(lq)) { printf("%d\n",DeQueue(lq)); } return 0; }
/* linkqueue.c */ #include<stdio.h> #include<stdlib.h> #include"linkqueue.h" // 创建空队 linkqueue CreateQueue() { linklist list = malloc(sizeof(Lnode)); linkqueue Lq = malloc(sizeof(Lqnode)); // 判断是否malloc到空间 if ( list == NULL ) { printf("malloc error!\n"); } // 判断是否malloc到空间 if ( Lq == NULL ) { printf("malloc error!\n"); } list->data = -1; list->next = NULL; Lq->front = list; Lq->rear = list; return Lq; } // 清空队列 int ClearQueue(linkqueue LQ) { // 如果链队不为空 while ( FALSE == EmptyQueue(LQ) ) { DeQueue(LQ); } return OK; } //获取队列长度 int GetLenth(linkqueue LQ) { int len = 0; while ( LQ->front != NULL ) { LQ->front = LQ->front->next; len++; } printf("len = %d\n",len); return len; } // 入队 data_t EnQueue(linkqueue LQ,data_t val) { // 如果链队为空 if ( TRUE == EmptyQueue(LQ) ) { //注意:如果是空队,注意修改尾指针指向 LQ->rear=LQ->front; } //生成一个新的节点 linklist s = malloc(sizeof(Lnode)); s->data = val; s->next = NULL; //插入到末尾 LQ->rear->next = s; LQ->rear = s; //修改尾指针 return val; } // 判断是否为空队 int EmptyQueue(linkqueue LQ) { //没有有效数据,只剩头节点 if ( LQ->front->next == NULL ) { return TRUE; } else { return FALSE; } } // 出队 data_t DeQueue(linkqueue LQ) { // 如果链队为空 if ( TRUE == EmptyQueue(LQ) ) { printf("queue is empty\n"); return ERROR; } linklist d = LQ->front->next; //记录删除节点位置 data_t val = d->data; //取值 LQ->front->next = d->next; //删除 free(d); //释放 /* if(TRUE == EmptyQueue(LQ)) // 判断是否为空 { LQ -> rear = LQ -> front; //队尾 指向 队头 } */ return val; } // 销毁 void DestroyQueue(linkqueue LQ) { linklist d = LQ->front; while ( d != NULL ) { d = d->next; free(d); } }
/* linkqueue.h */ #ifndef _LINKQUEUE_H #define _LINKQUEUE_H #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR -1 typedef int data_t; struct node{ data_t data; struct node *next; }; typedef struct node Lnode; typedef struct node *linklist; //将头尾指针包在一起 struct qnode{ linklist front; linklist rear; }; typedef struct qnode Lqnode; typedef struct qnode * linkqueue; int EmptyQueue(linkqueue LQ); // 清空队 data_t DeQueue(linkqueue LQ); // 出队 linkqueue CreateQueue(); // 创建空队 int ClearQueue(linkqueue LQ); // 清空队列 int GetLenth(linkqueue LQ); // 获取队列长度 data_t EnQueue(linkqueue LQ,data_t val); // 进队 void DestroyQueue(linkqueue LQ); // 销毁 #endif
数据结构链队
最新推荐文章于 2024-08-13 09:06:38 发布