//循環隊列 //CycQueue.h #define QUEUEMAX 15 typedef struct { DATA data[QUEUEMAX]; //隊列數組 int head; //隊頭 int tail; //隊尾 }CycQueue; CycQueue *CycQueueInit () { CycQueue *q; if(q=(CycQueue *)malloc(sizeof(CycQueue))) //申請保存隊列的內存 { q->head = 0; //設置隊頭 q->tail = 0; //設置隊尾 return q; }else return NULL; // 返回空 } void CycQueueFree(CycQueue *q) // 釋放隊列 { if(q!=NULL) free(q); } int CycQueueIsEmpty(CycQueue *q) // 隊列是否爲空 { return (q->head==q->tail) ; } int CycQueueIsFull (CycQueue *q) // 隊列是否已滿 { return ((q->tail+1)%QUEUEMAX == q->head) ; } int CycQueueIn(CycQueue *q,DATA data) // 入隊函數 { if((q->tail+1)%QUEUEMAX == q->head) { printf("隊列已滿!\n"); return 0; }else{ q->tail = (q->tail+1)%QUEUEMAX; //求列尾序號 q->data[q->tail] = data; return 1; } } DATA *CycQueueOut (CycQueue *q) // 循環隊列的出隊函數 { if(q->head == q->tail) { printf("隊列已空!\n"); return NULL; }else{ q->head=(q->head+1)%QUEUEMAX; return &(q->data[q->head]); } } int CycQueueLen(CycQueue *q) // 獲取隊列長度 { int n; n=q->tail-q->head; if(n<0) n=QUEUEMAX + n; return n; } DATA *CycQueuePeek(CycQueue *q) // 獲取隊列中第1個位置的數據 { if(q->head==q->tail) { printf("隊列已經爲空!\n"); return NULL; }else{ return &(q->data[(q->head+1)%QUEUEMAX]); } }
隊列學習筆記 循環隊列
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.