隊列的基本概念
隊列 (Queue) :也是運算受限的線性表。是一種先進先出 (First In First Out ,簡稱 FIFO) 的線性表。只允許在表的一端進行插入,而在另一端進行刪除。
隊首 (front) :允許進行刪除的一端稱為隊首。
隊尾 (rear) :允許進行插入的一端稱為隊尾。
#include<stdio.h> #include<stdlib.h> #define ElementType int #define ERROR -99 //構建結點信息 typedef struct Node{ ElementType data; struct Node *next; }QNode; //構建節點頭和尾指針,在隊列的的增加和刪除操作分別在尾和頭部執行 typedef struct { QNode *front; QNode *rear; }Queue; Queue* CreateQueue(){ //申請結點內存,成功返回大於零的值,否則返回NULL Queue* q = (Queue *)malloc(sizeof(Queue)); if(!q){ printf("內存空間不足\n"); return NULL; } //指針初值為NULL q->front = q->rear = NULL; return q; } void AddQ(Queue *q,ElementType item){ QNode* qNode=(QNode*)malloc(sizeof(QNode)); if(!qNode){ printf("內存空間不足\n"); exit(-1); } qNode->data = item; qNode->next = NULL; if(q->front==NULL){ q->front = qNode; } if(q->rear == NULL){ q->rear = qNode; } else{ //頭尾不為null,則執行下列操作 //連上上一個指針 q->rear->next=qNode; //隊尾指針從新被定義 q->rear=qNode; } } int IsEmptyQ(Queue* q){ return (q->front == NULL); } ElementType DeleteQ(Queue* q){ int item; if(IsEmptyQ(q)){ printf("空隊列\n"); return ERROR; } QNode *temp = q->front; if(q->rear == q->front){ q->rear=NULL; q->front=NULL; } else{ //在隊列頭指針進行操作 q->front = q->front->next; } item = temp->data; free(temp); return item; } void PrientQueue(Queue *q){ if(IsEmptyQ(q)){ printf("空隊列\n"); return ; } printf("打印隊列所有元素:\n"); QNode *qnode = q->front; while(qnode != NULL){ printf("%d",qnode->data); qnode= qnode->next; } printf("\n"); } int main(){ Queue *q = CreateQueue(); AddQ(q,1); AddQ(q,2); AddQ(q,3); AddQ(q,4); PrientQueue(q); DeleteQ(q); DeleteQ(q); PrientQueue(q); return 0; }
運行結果圖

