/* 隊列是一種操作受限的線性表,其限制為僅允許在表的一端插入,在表的另一端進行刪除。 進行刪除的一端稱為隊頭或隊首,插入元素稱為入隊,刪除元素稱為出隊。 在順序隊*q中,隊空條件為q->front==q->rear。隊滿條件為q->rear==MaxSize-1. 入隊操作為先將隊尾指針增加1,然后把e放在隊尾。 出隊操作是先將隊頭指針增加1,然后取出隊頭元素。*/#include <stdio.h>#include <stdlib.h>#define MaxSize 5typedef char ElemType;typedef struct{ ElemType data[MaxSize];//存放隊列中的元素 int front,rear;//隊頭和隊尾指針}SQQueue;//定義順序隊的類型void InitQueue(SqQueue *&q)//初始化順序隊{ q = (SqQueue *)malloc(sizeof(SqQueue)); q->front= q->rear= -1;}void DestroyQueue(SqQueue *&q)//銷毀順序隊{ free(q);}bool QueueEmpty(SqQueue *q)//判斷順序隊是否為空{ return (q->front==q->rear);}bool enQueue(SqQueue *&q,ElemType e)//入隊{ if(q->rear==MaxSize-1) return false; q->rear++; q->data[q->rear]=e; return true;}bool deQueue(SqQueue *&q,ElemType &e)//出隊{ if(q->rear==q->front) return false; q->front++; e = q->data[q->front]; return true ;}int main(){ ElemType e; SqQueue *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;}運行結果:
新聞熱點
疑難解答