/* 問題:對于環形隊列如果知道隊頭指針和隊列中元素的個數。設計出這種 環形隊列的基本操作。 分析: 隊尾指針rear=(front+count)%MaxSize 隊空條件:count==0. 隊滿條件:count==MaxSize。*/#include <stdio.h>#include <stdlib.h>#define MaxSize 5typedef char ElemType;typedef struct{ ElemType data[MaxSize];//存放隊列中的元素 int front;//定義隊頭指針 int count;//定義元素個數}QuType;//定義順序隊的類型void InitQueue(QuType *&q)//初始化順序隊{ q = (QuType *)malloc(sizeof(QuType)); q->front= 0; q->count = 0;}void DestroyQueue(QuType *&q)//銷毀順序隊{ free(q);}bool QueueEmpty(QuType *q)//判斷順序隊是否為空{ return (q->count==0);}bool enQueue(QuType *&q,ElemType e)//入隊{ int rear; if(q->count==MaxSize)//隊滿上溢出 return false; else { rear=(q->front+q->count)%MaxSize;//求隊尾位置 rear = (rear + 1)%MaxSize; q->data[rear]=e; q->count++; return true; }}bool deQueue(QuType *&q,ElemType &e)//出隊{ if(q->count==0)//對空下溢出 return false; else { q->front = (q->front + 1)%MaxSize; e = q->data[q->front]; q->count--; return true ; }}int main(){ ElemType e; QuType *q; PRintf("環形隊列基本運算如下:/n"); printf(" (1)初始化隊列q/n"); InitQueue(q); printf(" (2)依次進隊列元素a,b,c/n"); if (!enQueue(q,'a')) printf("/t提示:隊滿,不能進隊/n"); if (!enQueue(q,'b')) printf("/t提示:隊滿,不能進隊/n"); if (!enQueue(q,'c')) printf("/t提示:隊滿,不能進隊/n"); printf(" (3)隊列為%s/n",(QueueEmpty(q)?"空":"非空")); if (deQueue(q,e)==0) printf("隊空,不能出隊/n"); else printf(" (4)出隊一個元素%c/n",e); printf(" (5)依次進隊列元素d,e,f/n"); if (!enQueue(q,'d')) printf("/t提示:隊滿,不能進隊/n"); if (!enQueue(q,'e')) printf("/t提示:隊滿,不能進隊/n"); if (!enQueue(q,'f')) printf("/t提示:隊滿,不能進隊/n"); printf(" (6)出隊列序列:"); while (!QueueEmpty(q)) { deQueue(q,e); printf("%c ",e); } printf("/n"); printf(" (7)釋放隊列/n"); DestroyQueue(q); return 0;}運行結果:
|
新聞熱點
疑難解答