隊列特性:先進先出(FIFO)——先進隊列的元素先出隊列。來源於我們生活中的隊列(先排隊的先辦完事)。
隊列有下面幾個操作:
- InitQueue() ——初始化隊列
- EnQueue() ——進隊列
- DeQueue() ——出隊列
- IsQueueEmpty()——判斷隊列是否為空
- IsQueueFull() ——判斷隊列是否已滿
隊列可以由數組和鏈表兩種形式實現隊列操作(c語言),下面僅以數組為例:
數組實現:
隊列數據結構
typedef struct queue { int queuesize; //數組的大小 int head, tail; //隊列的頭和尾下標 int *q; //數組頭指針 }Queue;
InitQueue() ——初始化隊列
void InitQueue(Queue *Q) { Q->queuesize = 8; Q->q = (int *)malloc(sizeof(int) * Q->queuesize); //分配內存 Q->tail = 0; Q->head = 0; }
這樣有個缺陷,空間利用率不高。采用循環隊列:
EnQueue() ——進隊列
void EnQueue(Queue *Q, int key) { int tail = (Q->tail+1) % Q->queuesize; //取余保證,當quil=queuesize-1時,再轉回0 if (tail == Q->head) //此時隊列沒有空間 { printf("the queue has been filled full!"); } else { Q->q[Q->tail] = key; Q->tail = tail; } }
DeQueue() ——出隊列
int DeQueue(Queue *Q) { int tmp; if(Q->tail == Q->head) //判斷隊列不為空 { printf("the queue is NULL\n"); } else { tmp = Q->q[q->head]; Q->head = (Q->head+1) % Q->queuesize; } return tmp; }
IsQueueEmpty()——判斷隊列是否為空
int IsQueueEmpty(Queue *Q) { if(Q->head == Q->tail) { return 1; } else { return 0; } }
IsQueueFull()——判斷隊列是否已滿
int IsQueueFull(Queue *Q) { if((Q->tail+1)% Q->queuesize == Q->head) { return 1; } else { return 0; } }