1. 程式人生 > >數據結構-循環隊列程序演示

數據結構-循環隊列程序演示

bool stdio.h front printf 不一定 urn 存儲結構 需要 typedef

  1 /*
  2 循環隊列需要2個參數來確定;
  3 front,rear
  4 1)隊列初始化
  5 front和rear的值都為零
  6 2)隊列非空
  7 front代表的是隊列的第一個元素
  8 rear代表的是隊列的最後一個有效元素
  9 3)隊列空
 10 front和rear的值相等,但不一定是零
 11 */
 12 
 13 
 14 /*
 15 隊列
 16 定義:一種可以實現先進先出的存儲結構
 17 分類:
 18 靜態隊列
 19 鏈式隊列
 20 */
 21 #include <stdio.h>
 22 #include <malloc
.h> 23 24 typedef struct Queue 25 { 26 int *pBase; 27 int front; 28 int rear; 29 }QUEUE; 30 31 void init(QUEUE *); 32 bool en_queue(QUEUE*, int val); 33 void traverse_queue(QUEUE*); 34 void out_queue(QUEUE *, int*); 35 bool full_queue(QUEUE*); 36 bool empty_queue(QUEUE*);
37 38 int main(void) 39 { 40 QUEUE Q; 41 int val; 42 init(&Q); 43 en_queue(&Q, 0); 44 en_queue(&Q, 1); 45 en_queue(&Q, 2); 46 en_queue(&Q, 3); 47 en_queue(&Q, 4); 48 en_queue(&Q, 5); 49 en_queue(&Q, 6); 50 en_queue(&Q, 7
); 51 en_queue(&Q, 8); 52 traverse_queue(&Q); 53 if (out_queue(&Q, &val)) 54 { 55 printf("出隊成功,隊列出隊的元素為:%d\n",val); 56 } 57 else 58 { 59 printf("出隊失敗!\n"); 60 } 61 traverse_queue(&Q); 62 return 0; 63 } 64 65 void init(QUEUE *pQ) 66 { 67 pQ->pBase = (int*)malloc(sizeof(int) * 6); 68 pQ->front = 0; 69 pQ->rear = 0; 70 } 71 72 bool en_queue(QUEUE *pQ, int val) 73 { 74 if (full_queue(pQ)) 75 { 76 return false; 77 } 78 else 79 { 80 pQ->pBase[pQ->rear] = val; 81 pQ->rear = (pQ->rear + 1) % 6; 82 return true; 83 } 84 } 85 86 bool full_queue(QUEUE*pQ) 87 { 88 if (pQ->front == (pQ->rear+1)%6) 89 { 90 return true; 91 } 92 else 93 { 94 return false; 95 } 96 } 97 98 void traverse_queue(QUEUE *pQ) 99 { 100 int i = pQ->front; 101 while (i != pQ->rear) 102 { 103 printf("%d ", pQ->pBase[i]); 104 i = (i + 1) % 6; 105 } 106 return; 107 } 108 109 bool empty_queue(QUEUE *pQ) 110 { 111 if (pQ->front == pQ->rear) 112 { 113 return true; 114 } 115 else 116 { 117 return false; 118 } 119 } 120 121 bool out_queue(QUEUE*pQ, int* pVal) 122 { 123 if (empty_queue(pQ)) 124 { 125 return false; 126 } 127 else 128 { 129 *pVal = pQ->pBase[pQ->front]; 130 pQ->front = (pQ->front + 1) % 6; 131 return true; 132 } 133 }

數據結構-循環隊列程序演示