代码如下:
#include<stdio.h> #include<stdlib.h> typedef char ElemType; typedef struct QNode { ElemType date; struct QNode *next; }QNode , *QueuePtr; typedef struct { QueuePtr front , rear; }LinkQueue; ///////////////////////////////// //创建一个队列 void InitQueue(LinkQueue *q) { q->front = q->rear = (QueuePtr)malloc(sizeof(QNode)); if (!q->front) { exit(0); } q->front->next = NULL; } /////////////////////////////////// //入队列操作 void EnQueue(LinkQueue *q , ElemType e) { QueuePtr p; p = (QueuePtr)malloc(sizeof(QNode)); if (!q->front) { exit(0); } p->date = e; p->next = NULL; q->rear->next = p; q->rear = p; } //////////////////////////////////// //出队列操作 void DeQueue(LinkQueue *q , ElemType *e) { if (q->front == q->rear) { return; } QueuePtr p = q->front->next; *e = p->date; q->front->next = p->next; if (q->rear == p) { q->rear = q->front; } free(p); } ///////////////////////////////////// //销毁一个队列 void DestoryQueue(LinkQueue *q) { while (q->front) { q->rear = q->front->next; free(q->front); q->front = q->rear; } } /////////////////////////////////////// //计算队列长度 int LenQueue(LinkQueue *q) { int i; QueuePtr p = q->front->next; for (i = 0; p!=NULL; i++) { p = p->next; } return i; } int main() { LinkQueue q; InitQueue(&q); ElemType e; printf("请输入要入队列的字符串:"); while ((e = getchar()) != ' ') { if (e!=' ') { EnQueue(&q , e); } } printf("正在打印字符串:"); QueuePtr p = q.front->next; for (int i = 0; i < LenQueue(&q); i++) { printf("%c",p->date); p = p->next; } putchar(' '); printf("正在销毁队列..."); DestoryQueue(&q); printf("销毁成功!"); return 0; }
运行结果: