? ? ? 此處的鏈式與循環隊列可以應用于BFS和樹的層序遍歷。下面是對其結構和基本操作的程序描述。
1、循環隊列
? ? 解決循環隊列的隊空和隊滿的方法:
? ? [1].增加一個參數count,用來記錄數組中當前元素的個數;
? ? [2].為避免隊空和滿兩狀態混淆,少用一個存儲空間,也就是數組最后一個存數空間不用,(rear+1)% QSIZE= front 時, 隊滿;
? ? ? ?a)判斷是否為空隊列:front==rear; b)判斷隊列是否已滿:front=(rear+1)%size; ?
1 typedef struct{ //隊列結構定義 2 int front; 3 int rear; 4 int count; //隊列元素計數 5 int key[QSIZE]; 6 }BFSQueue; 7 8 void InitBFSQueue(BFSQueue *BFSQ) //隊列初始化 9 { 10 BFSQ->front=0; //front指向隊列第一個元素 11 BFSQ->rear=0; //rear指向隊列中下一個空位 12 BFSQ->count=0; 13 } 14 int EmptyBFSQueue(BFSQueue *BFSQ) //空 15 { 16 return BFSQ->count==0; 17 } 18 int FullBFSQueue(BFSQueue *BFSQ) //滿 19 { 20 return BFSQ->count==QSIZE; 21 } 22 23 void AddBFSQueue(BFSQueue *BFSQ,int num) //插入 24 { 25 if(!FullBFSQueue(BFSQ)) 26 { 27 BFSQ->count++; 28 BFSQ->key[BFSQ->rear]=num; 29 BFSQ->rear=(BFSQ->rear+1) % QSIZE; 30 } 31 } 32 33 int DelBFSQueue(BFSQueue *BFSQ) //刪除 34 { 35 int temp; 36 if(!EmptyBFSQueue(BFSQ)) 37 { 38 BFSQ->count--; 39 temp=BFSQ->key[BFSQ->front]; 40 BFSQ->front=(BFSQ->front+1) % QSIZE; 41 return temp; 42 } 43 else 44 return NULL; 45 } 46 /******************************************************************/
2、鏈式隊列
1 typedef struct QNode{ // 隊列元素結構
2 int key;
3 struct QNode *next;
4 }QNode;
5 typedef struct{ // 隊列結構
6 QNode *front;
7 QNode *rear;
8 int count;
9 }BFSQueue;
10
11 void InitBFSQueue(BFSQueue *BFSQ) //隊列初始化
12 {
13 BFSQ->front=NULL;
14 BFSQ->rear=NULL;
15 BFSQ->count=0;
16 }
17 int EmptyBFSQueue(BFSQueue *BFSQ) //空
18 {
19 return BFSQ->count==0;
20 }
21
22 void AddBFSQueue(BFSQueue *BFSQ,int num) //插入
23 {
24 QNode *np=(QNode *)malloc(sizeof(QNode));
25 np->key=num;
26 np->next=NULL;
27 //BFSQ->count++;
28
29 if(!EmptyBFSQueue(BFSQ)) // 隊列非空
30 {
31 BFSQ->rear->next=np;
32 BFSQ->rear=np;
33 }
34 else // 隊列空
35 {
36 BFSQ->rear=np;
37 BFSQ->front=np;
38 }
39 BFSQ->count++;
40 }
41 int DelBFSQueue(BFSQueue *BFSQ) //刪除
42 {
43 int temp;
44 QNode *tp=(QNode *)malloc(sizeof(QNode));
45 if(!EmptyBFSQueue(BFSQ)) //隊列非空
46 {
47 //BFSQ->count--; //注意,必須在隊列判定之后增加或減小count的值///
48 tp=BFSQ->front;
49 temp=tp->key;
50 if(BFSQ->count==1) //出隊后隊列為空
51 {
52 BFSQ->rear=NULL;
53 BFSQ->front=NULL;
54 }
55 else //出隊后隊列非空
56 {
57 BFSQ->front=tp->next;
58 }
59 BFSQ->count--;
60 free(tp); //釋放暫存指針
61
62 return temp;
63 }
64 else
65 return NULL;
66 }