1. 程式人生 > 實用技巧 >非迴圈佇列

非迴圈佇列

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 typedef char DataType;
 5 
 6 #define QueueSize 40
 7 
 8 typedef struct {
 9     DataType data[QueueSize];
10     //定義佇列的頭部、尾部,像排隊打飯一樣,從尾巴rear進,從front頭部出
11     int front, rear;
12 }SqQueue;
13 
14 //初始化佇列
15 void InitQueue(SqQueue &Q)
16
{ 17 Q.rear = Q.front = 0; 18 } 19 20 //判斷佇列是否為空 21 bool QueueEmpty(SqQueue Q) 22 { 23 if (Q.front == Q.rear) 24 { 25 return true; 26 } 27 else 28 { 29 return false; 30 } 31 } 32 33 //入隊操作 34 bool EnterQueue(SqQueue &Q, DataType x) 35 { 36 //判斷佇列是否已滿 37 if
(Q.rear == QueueSize - 1) 38 { 39 return false; 40 } 41 else 42 { 43 Q.data[Q.rear] = x; 44 Q.rear += 1;//隊尾指標向後移動一個位置 45 return true; 46 } 47 } 48 49 //出隊操作 50 bool DeleteQueue(SqQueue &Q, DataType &x) 51 { 52 //出隊刪除時先判斷隊空 53 if (Q.front==Q.rear)
54 { 55 return false; 56 } 57 else 58 { 59 x = Q.data[Q.front]; 60 Q.front += 1; 61 return true; 62 } 63 } 64 65 int main() 66 { 67 char str[] = "ABCDEFGH"; 68 char x; 69 70 SqQueue Q; 71 InitQueue(Q); 72 73 74 for (int i = 0; i < sizeof(str) - 1; i++) 75 { 76 //將字串中的資料插入佇列 77 EnterQueue(Q, str[i]); 78 } 79 80 DeleteQueue(Q, x); 81 printf("出佇列的元素為:%c\n", x); 82 83 printf("順序佇列中的元素為:"); 84 //判斷是否佇列不為空 85 if (QueueEmpty(Q) == false) 86 { 87 //這裡迴圈時要注意用佇列的頭和尾進行迴圈 88 for (int i = Q.front; i < Q.rear; i++) 89 { 90 printf("%c", Q.data[i]); 91 } 92 } 93 94 95 96 97 getchar(); 98 return 0; 99 }