数据结构--队列--链式存储
队列一般叫优先级队列.这是跟它的相关应用有关的.
#include <stdio.h> #include <stdlib.h> typedef int elemType; struct sNode{ /*队列节点*/ elemType data; struct sNode *next; }; struct queueLK{ struct sNode *front; /*队列头指针*/ struct sNode *rear; /*队列尾指针*/ }; /* 1.初始化链队*/ void initQueue(struct queueLK *hq) { hq->front = hq->rear = NULL; return; } /* 2.向链队中插入一个元素*/ void enQueue(struct queueLK *hq, elemType x) { struct sNode *newP; newP = malloc(sizeof(struct sNode)); if(newP == NULL) { printf("空间申请失败!\n"); system("pause"); } newP->data = x; newP->next = NULL; if(hq->rear == NULL) { hq->front = hq->rear = newP; }else{ hq->rear->next = newP; hq->rear = newP; } return; } /* 3.从队列中删除一个元素*/ elemType outQueue(struct queueLK *hq) { if(hq->front == NULL) { printf("队列为空...\n"); return -1; } struct sNode *temp = hq->front; elemType data = temp->data; if(hq->front == hq->rear) /*若只有一个节点*/ { hq->front = hq->rear = NULL; }else{ hq->front=hq->front->next; } free(temp); return data; } /* 4.读取队首元素*/ elemType peekQueue(struct queueLK *hq) { if(hq->front == NULL) { printf("队列为空,读取失败.\n"); return -1; } return hq->front->data; } /* 5.检查链队是否为空,若为空返回1,否则返回0*/ int emptyQueue(struct queueLK *hq) { if(hq->front == NULL) { return 1; }else{ return 0; } } /* 6.清楚队列中的所有元素*/ void clearQueue(struct queueLK *hq) { if(hq->front == NULL) { return; } struct sNode *temp = hq->front; while(hq->front != NULL) { hq->front = hq->front->next; free(temp); temp = hq->front; } hq->rear = NULL; } #if 1 int main() { struct queueLK hq; int a[] = {2,4,5}; int i; initQueue(&hq); for(i = 0;i<sizeof(a)/4;i++) { enQueue(&hq,a[i]); } if(emptyQueue(&hq)) { printf("队列为空...\n"); } printf("队列头为:%d\n",peekQueue(&hq)); printf("出队列:%d\n",outQueue(&hq)); printf("出队列:%d\n",outQueue(&hq)); printf("出队列:%d\n",outQueue(&hq)); printf("入队列...\n"); enQueue(&hq,7); printf("队列头为:%d\n",peekQueue(&hq)); clearQueue(&hq); printf("清空队列.\n"); if(emptyQueue(&hq)) { printf("队列为空...\n"); } system("pause"); return 0; } #endif
************************************************************************
运行结果
************************************************************************
队列头为:2 出队列:2 出队列:4 出队列:5 入队列... 队列头为:7 清空队列. 队列为空... 请按任意键继续. . .