1.队列的基础
队列是插入只能在一端(后端),删除只能在另一端(前端)的线性表,是先进先出模型。
1. 入队:在表的末端插入;
2. 出队:在表的开头删除元素;
2.队列的应用
汽车加油站
模拟打印机缓冲区
CPU分时系统、计算机网络
打印杨辉三角
3.队列的数组实现
1. fatal.h
#include <stdio.h> #include <stdlib.h> #define Error( Str ) FatalError( Str ) #define FatalError( Str ) fprintf( stderr, "%s ", Str ),system("puase"),getchar(),exit( 1 )
2.queue.h
#include <stdio.h> typedef int ElementType; #ifndef _Queue_h struct QueueRecord; typedef struct QueueRecord *Queue; int IsEmpty(Queue Q); int IsFull(Queue Q); Queue CreateQueue(int MaxElements); void DisposeQueue(Queue Q); void MakeEmpty(Queue Q); void Enqueue(ElementType X, Queue Q); ElementType Front(Queue Q); void Dequeue(Queue Q); ElementType FrontAndDequeue(Queue Q); #endif
3.queue.c
#include "queue.h" #include "fatal.h" #include <stdlib.h> #define MinQueueSize (5) struct QueueRecord { int Capacity; int Front; int Rear; int Size; ElementType *Array; }; int IsEmpty(Queue Q) { return Q->Size == 0; } Queue CreateQueue(int MaxElements) { Queue Q; if (MaxElements < MinQueueSize) { Error("Queue is too small "); } Q = malloc(sizeof(struct QueueRecord)); if (Q==NULL) { FatalError("out of space!!!"); } Q->Array = malloc(sizeof(ElementType)*MaxElements); if (Q->Array == NULL) { FatalError("out of space!!!"); } Q->Capacity = MaxElements; MakeEmpty(Q); return Q; } int IsFull(Queue Q) { return Q->Size == Q->Capacity; } void MakeEmpty(Queue Q) { Q->Size = 0; Q->Front = 1; Q->Rear = 0; } ElementType Front(Queue Q) { if (!IsEmpty(Q)) { return Q->Array[Q->Front]; } Error("Empty Queue "); return 0; } static int Succ(int Value, Queue Q) { if (++Value==Q->Capacity) { Value = 0; } return Value; } void Enqueue(ElementType X, Queue Q) { if (IsFull(Q)) { Error("Full Queue "); } else { Q->Size++; Q->Rear = Succ(Q->Rear, Q); Q->Array[Q->Rear] = X; } } void Dequeue(Queue Q) { if (!IsEmpty(Q)) { Q->Size--; Q->Front = Succ(Q->Front, Q); } else { Error("Empty Queue "); } } ElementType FrontAndDequeue(Queue Q) { ElementType X = 0; if (IsEmpty(Q)) { Error("Empty Queue "); } else { Q->Size--; X = Q->Array[Q->Front]; Q->Front = Succ(Q->Front, Q); } return X; } void DisposeQueue(Queue Q) { if (Q!=NULL) { free(Q->Array); free(Q); Q = NULL; } }
4.testqueue.c
#include "queue.h" #include "fatal.h" #include <stdio.h> #include <stdlib.h> void main() { Queue Q; Q = CreateQueue(10); for (int i = 0; i < 10; i++) { Enqueue(i, Q); } for (int i = 0; i < 10; i++) { ElementType data = Front(Q); printf("%d ", data); Dequeue(Q); } printf(" "); for (int i = 0; i < 10; i++) Enqueue(i, Q); for (int i = 0; i < 10; i++) { ElementType data = FrontAndDequeue(Q); printf("%d ", data); } printf(" "); DisposeQueue(Q); system("pause"); }