From df89c59261608abef3300d0a48b87e87c1957a5b Mon Sep 17 00:00:00 2001 From: Xu Bai <1373953675@qq.com> Date: Wed, 3 Jul 2019 22:40:00 +0800 Subject: [PATCH] =?UTF-8?q?l=E9=93=BE=E9=98=9F=E5=9F=BA=E6=9C=AC=E6=93=8D?= =?UTF-8?q?=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- _02.栈与队列/_f.链队列.c | 80 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 76 insertions(+), 4 deletions(-) diff --git a/_02.栈与队列/_f.链队列.c b/_02.栈与队列/_f.链队列.c index 81e0030..49dc697 100644 --- a/_02.栈与队列/_f.链队列.c +++ b/_02.栈与队列/_f.链队列.c @@ -3,6 +3,7 @@ #include "io.h" #define MAXSIZE 20 +#define OVERFLOW -1 #define OK 1 #define ERROR 0 #define TRUE 1 @@ -33,13 +34,13 @@ Status InitQueue(LinkQueue *Q) Q->front = Q->rear = (QueuePtr)malloc(sizeof(QNode)); if (!Q->front) { - exit(-1); + exit(OVERFLOW); } Q->front->next = NULL; return OK; } -Status Destroy(LinkQueue *Q) +Status DestroyQueue(LinkQueue *Q) { while (Q->front) { @@ -101,6 +102,77 @@ Status GetHead(LinkQueue Q, ElemType *e) return OK; } -Status EnQueue(LinkQueue *Q,ElemType e){ - Q +Status EnQueue(LinkQueue *Q, ElemType e) +{ + QueuePtr p = (QueuePtr)malloc(sizeof(QNode)); + if (!p) + { + exit(OVERFLOW); + } + p->data = e; + p->next = NULL; + Q->rear->next = p; //Ìí¼Óµ½Á´Î² + Q->rear = p; + return OK; +} + +Status DeQueue(LinkQueue *Q, ElemType *e) +{ + if (Q->rear == Q->front) + { + return ERROR; + } + QueuePtr p = Q->front->next; + *e = p->data; + Q->front->next = p->next; + if (Q->rear == p) + { + // ÈôÁ´±í³ýÍ·½ÚµãÍâֻʣÏÂÒ»¸öÔªËØÊ±£¬ÔòÐ轫rearÖ¸ÏòÍ·½Úµã + //Èô¶ÓÍ·¾ÍÊǶÓ⣬Ôòɾ³ýºó½«rearÖ¸Ïòfront + Q->rear = Q->front; + } + free(p); + return OK; +} + +Status QueueTraverse(LinkQueue Q) +{ + QueuePtr p; + p = Q.front->next; + while (p) + { + visit(p->data); + p = p->next; + } + printf("\n"); + return OK; +} + +int main() +{ + ElemType e; + LinkQueue q; + int i = InitQueue(&q); + if (i) + { + printf("inited! \n"); + printf("ÊÇ·ñ¿Õ¶ÓÁУ¿", QueueEmpty(q)); + } + EnQueue(&q, -5); + EnQueue(&q, 5); + EnQueue(&q, 10); + printf("²åÈë3¸öÔªËØ(-5,5,10)ºó,¶ÓÁеij¤¶ÈΪ%d\n", QueueLength(q)); + QueueTraverse(q); + i = GetHead(q, &e); + if (i == OK) + printf("¶ÓÍ·ÔªËØÊÇ£º%d\n", e); + DeQueue(&q, &e); + printf("ɾ³ýÁ˶ÓÍ·ÔªËØ%d\n", e); + QueueTraverse(q); + ClearQueue(&q); + printf("Çå¿Õ¶ÓÁкó,q.front=%u q.rear=%u q.front->next=%u\n",q.front,q.rear,q.front->next); + DestroyQueue(&q); + printf("Ïú»Ù¶ÓÁкó,q.front=%u q.rear=%u\n",q.front, q.rear); + getchar(); + } \ No newline at end of file