資料結構之自建演算法庫——順序環形佇列
阿新 • • 發佈:2019-01-27
按照“0207將演算法變程式”[視訊]部分建議的方法,建設自己的專業基礎設施演算法庫。
下圖是資料儲存結構設計及各種操作實現的要點:
順序環形佇列演算法庫採用程式的多檔案組織形式,包括兩個檔案:
1.標頭檔案:sqqueue.h,包含定義順序環形佇列資料結構的程式碼、巨集定義、要實現演算法的函式的宣告;
#ifndef SQQUEUE_H_INCLUDED
#define SQQUEUE_H_INCLUDED
#define MaxSize 5
typedef 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;
}