头文件Queue.h
#include<stdio.h> #include<stdbool.h> #include<malloc.h> #include<assert.h> typedef int ElemType; typedef struct QueueNode { ElemType data; struct QueueNode *next; }QueueNode; typedef struct LinkQueue { QueueNode *front; QueueNode *tail; }LinkQueue; void InitQueue(LinkQueue *Q); void EnQueue(LinkQueue *Q,ElemType x); void DeQueue(LinkQueue *Q); bool IsEmptyQueue(LinkQueue *Q); void ShowQueue(LinkQueue *Q); void GetHead(LinkQueue *Q, ElemType *v); ElemType Length(LinkQueue *Q); void Clear(LinkQueue *Q); void Destroy(LinkQueue *Q);
函数实现Queue.c
#include"Queue.h" void InitQueue(LinkQueue *Q) { QueueNode *s = (QueueNode*)malloc(sizeof(QueueNode)); assert(s != NULL); Q->front = Q->tail = s; Q->tail->next = NULL; } bool IsEmptyQueue(LinkQueue *Q) { return Q->front == Q->tail; } void EnQueue(LinkQueue *Q, ElemType x) { QueueNode *s = (QueueNode*)malloc(sizeof(QueueNode)); assert(s != NULL); s->data = x; s->next = NULL; Q->tail->next = s; Q->tail = s; } void DeQueue(LinkQueue *Q) { if (Q->front == Q->tail) return; QueueNode *p = Q->front->next; Q->front->next = p->next; free(p); if (p == Q->tail) Q->tail = Q->front; } void ShowQueue(LinkQueue *Q) { QueueNode *p = Q->front->next; printf("Front:>"); while (p != NULL) { printf("%d ", p->data); p = p->next; } printf("<:Tail"); } void GetHead(LinkQueue *Q, ElemType *v) { if (Q->front == Q->tail) return; QueueNode *p = Q->front->next; *v = p->data; } ElemType Length(LinkQueue *Q) { int len = 0; QueueNode *p = Q->front->next; while (p != NULL) { len++; p = p->next; } return len; } void Clear(LinkQueue *Q) { QueueNode *p = Q->front->next; if (Q->front == Q->tail) return; while (p != NULL) { Q->front->next = p->next; free(p); p = Q->front->next; } Q->tail = Q->front; } void Destroy(LinkQueue *Q) { Clear(Q); free(Q->front); Q->front = Q->tail = NULL; }
测试函数Main.c
#include"Queue.h" int main() { LinkQueue Q; InitQueue(&Q); for (int i = 1; i <= 10; ++i) { EnQueue(&Q,i); } ShowQueue(&Q); printf("\n"); DeQueue(&Q); ShowQueue(&Q); printf("\n"); printf("len=%d", Length(&Q)); }