對於C語言的隊列來說,也有順序存儲和鏈表存儲兩種方式。
順序存儲容量固定,鏈表存儲隨時分配釋放更加靈活。
下面是鏈表實現的隊列初始化、入隊、出隊函數實現:
#include<stdio.h> #include <malloc.h> #include <stdlib.h> typedef struct Node { int val; struct Node* next; }NODE, * PNODE; typedef struct Queue { PNODE front, rear; }QUEUE, *PQUEUE; void InitQueue(PQUEUE queue) { queue->front = queue->rear = (PNODE)malloc(sizeof(NODE)); if (queue->front == NULL) { printf("沒有足夠內存空間,錯誤\n"); } queue->front->next = NULL; } void InsertQueue(PQUEUE queue, int val) { PNODE tmp = (PNODE)malloc(sizeof(NODE)); if (tmp == NULL) { printf("無足夠內存空間,錯誤\n"); } tmp->val = val; tmp->next = NULL; queue->rear->next = tmp; queue->rear = queue->rear->next; tmp = NULL; } int DeleteQueue(PQUEUE queue) { if (queue->front == queue->rear) { printf("隊列為空\n"); } PNODE p = NULL; int val; p = queue->front->next; queue->front->next = p->next; val = p->val; free(p); p = NULL; return val; } int main(void) { QUEUE queue; InitQueue(&queue); InsertQueue(&queue, 1); InsertQueue(&queue, 2); InsertQueue(&queue, 3); for (int i = 0; i < 3; i++) printf("%d\n", DeleteQueue(&queue)); return 0; }
注意:在定義隊列的時候,不能定義PQUEUE,因為他是一個指針,在定義時需要指向NULL,但是指向NULL的指針是不允許對內部的結點進行任何操作的,因此需要定義QUEUE。
再通過&queue將隊列指針傳遞進去。