/* Queue.h */ #ifndef QUEUE_H_INCLUDED #define QUEUE_H_INCLUDED #include <stdio.h> #include <stdlib.h> struct Queue_Array { int element; struct Queue_Array* next; }; typedef struct Queue_Array* Q_Array; struct _Queue { Q_Array q; Q_Array Front; Q_Array Rear; }; typedef struct _Queue* Queue; /* Queue Operation */ int isEmpty(Queue Q); void CreateQueue(Queue Q); void make_Queue_Empty(Queue Q); void Enqueue(int Elmt, Queue Q); int Front(Queue Q); void Dequeue(Queue Q); int FrontAndDequeue(Queue Q); void printQueue(Queue Q); #endif // QUEUE_H_INCLUDED
/* Queue.c */ #include "Queue.h" int isEmpty(Queue Q) { return (Q->Front == Q->Rear); } void CreateQueue(Queue Q) { Q_Array q = (Q_Array)malloc(sizeof(struct Queue_Array)); q->element = 0; q->next = NULL; Q->Front = Q->Rear = q; } void Enqueue(int Elmt, Queue Q) { Q_Array q = (Q_Array) malloc (sizeof(struct Queue_Array)); q->element = Elmt; q->next = NULL; Q->Rear->next = q; Q->Rear = q; } int Front(Queue Q) { return Q->Front->element; } void Dequeue(Queue Q) { Q_Array q = Q->Front; Q->Front = Q->Front->next; free(q); } int FrontAndDequeue(Queue Q) { int frontElmt; Q_Array q = Q->Front; frontElmt = q->element; Q->Front = Q->Front->next; free(q); return frontElmt; } void make_Queue_Empty(Queue Q) { Q_Array q = Q->Front; while(q != Q->Rear) { Q->Front = Q->Front->next; free(q); q = Q->Front; } Q->Front = Q->Rear = NULL; Q->q = NULL; free(q); } void printQueue(Queue Q) { Q_Array q = Q->Front; while (q != Q->Rear->next) { printf("%d ", q->element); q = q->next; } printf(" "); }
测试:
/* main.c */ #include "Queue.h" int main() { Queue Q = (Queue) malloc (sizeof(struct _Queue)); Q->Front = NULL; Q->q = NULL; Q->Rear = NULL; CreateQueue(Q); Enqueue(1, Q); Enqueue(3, Q); Enqueue(5, Q); Enqueue(7, Q); Enqueue(9, Q); Enqueue(11, Q); printQueue(Q); Dequeue(Q); printQueue(Q); printf("Queue's front element is %d ", Front(Q)); FrontAndDequeue(Q); printf("Queue's front element is %d ", Front(Q)); printQueue(Q); return 0; }
结果: