資料結構之自建演算法庫——順序環形隊列,自建演算法環形隊列
本文針對資料結構基礎系列網路課程(3):棧和隊列中第9課時環形隊列的儲存及基本操作。
按照“0207將演算法變程式”[視頻]部分建議的方法,建設自己的專業基礎設施演算法庫。
順序環形隊列演算法庫採用程式的多檔案組織形式,包括兩個檔案:
1.標頭檔:sqqueue.h,包含定義順序環形隊列資料結構的代碼、宏定義、要實現演算法的函數的聲明;
#ifndef SQQUEUE_H_INCLUDED#define SQQUEUE_H_INCLUDED#define MaxSize 5typedef char ElemType;typedef struct{ ElemType data[MaxSize]; int front,rear; /*隊首和隊尾指標*/} SqQueue;void InitQueue(SqQueue *&q); //初始化順序環形隊列void DestroyQueue(SqQueue *&q); //銷毀順序環形隊列bool QueueEmpty(SqQueue *q); //判斷順序環形隊列是否為空白int QueueLength(SqQueue *q); //返回隊列中元素個數,也稱隊列長度bool enQueue(SqQueue *&q,ElemType e); //進隊bool deQueue(SqQueue *&q,ElemType &e); //出隊#endif // SQQUEUE_H_INCLUDED
2.源檔案:sqqueue.cpp,包含實現各種演算法的函數的定義
#include <stdio.h>#include <malloc.h>#include "sqqueue.h"void InitQueue(SqQueue *&q) //初始化順序環形隊列{ q=(SqQueue *)malloc (sizeof(SqQueue)); q->front=q->rear=0;}void DestroyQueue(SqQueue *&q) //銷毀順序環形隊列{ free(q);}bool QueueEmpty(SqQueue *q) //判斷順序環形隊列是否為空白{ return(q->front==q->rear);}int QueueLength(SqQueue *q) //返回隊列中元素個數,也稱隊列長度{ return (q->rear-q->front+MaxSize)%MaxSize;}bool enQueue(SqQueue *&q,ElemType e) //進隊{ if ((q->rear+1)%MaxSize==q->front) //隊滿上溢出 return false; q->rear=(q->rear+1)%MaxSize; q->data[q->rear]=e; return true;}bool deQueue(SqQueue *&q,ElemType &e) //出隊{ if (q->front==q->rear) //隊空下溢出 return false; q->front=(q->front+1)%MaxSize; e=q->data[q->front]; return true;}
3.在同一項目(project)中建立一個源檔案(如main.cpp),編製main函數,完成相關的測試工作。 例:
#include <stdio.h>#include "sqqueue.h"int main(){ ElemType e; SqQueue *q; printf("(1)初始化隊列q\n"); InitQueue(q); printf("(2)依次進隊列元素a,b,c\n"); if (enQueue(q,'a')==0) printf("隊滿,不能進隊\n"); if (enQueue(q,'b')==0) printf("隊滿,不能進隊\n"); if (enQueue(q,'c')==0) printf("隊滿,不能進隊\n"); printf("(3)隊列為%s\n",(QueueEmpty(q)?"空":"非空")); if (deQueue(q,e)==0) printf("隊空,不能出隊\n"); else printf("(4)出隊一個元素%c\n",e); printf("(5)隊列q的元素個數:%d\n",QueueLength(q)); printf("(6)依次進隊列元素d,e,f\n"); if (enQueue(q,'d')==0) printf("隊滿,不能進隊\n"); if (enQueue(q,'e')==0) printf("隊滿,不能進隊\n"); if (enQueue(q,'f')==0) printf("隊滿,不能進隊\n"); printf("(7)隊列q的元素個數:%d\n",QueueLength(q)); printf("(8)出隊列序列:"); while (!QueueEmpty(q)) { deQueue(q,e); printf("%c ",e); } printf("\n"); printf("(9)釋放隊列\n"); DestroyQueue(q); return 0;}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。