#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef
struct
node * PNode;
/*定義隊列的每個節點的類型*/
typedef
struct
node {
int
data;
//每個節點中存放的數據
PNode next;
//下一節點
}Node;
typedef
struct
queue {
PNode head;
//隊頭
PNode tail;
//隊尾
int
Length;
//隊列長度
}Queue;
Queue *GetQueue() {
// 返回創建的新空隊列
Queue *queue = (Queue *)
malloc
(
sizeof
(Queue)); //創建存放隊列的空間,字節大小為Queue,字針(32位系統)是4字節,int是4字節,那么node結構體就是8字節,queue就是8+8+4=20字節的
queue->head = (Node *)
malloc
(
sizeof
(Node)); //創建頭指針結點的存放空間
queue->head->next = NULL; //頭指針指向空指針
queue->tail = queue->head; //令隊列的尾指針為隊列的頭指針,這是為了在第一個元素入隊時,頭指針的字針能夠指向第一個元素。
queue->Length = 0;
return
queue;
}
void
EnQueue(Queue *Q,
int
x) {
// 將x送入隊,每次都是在隊尾加入新結點
PNode newnode = (Node *)
malloc
(
sizeof
(Node));//產生新的結點
newnode->data = x; //新的結點數據域存放輸入的x
++Q->Length; //隊列長度加一
newnode->next = NULL; //新產生的結點指向空指針
Q->tail->next = newnode; // 隊尾指針指向新結點,當第一個元素x進來的時候,隊尾指針相當於隊頭指針,那么也就是隊頭指針指向第一個進來的元素
Q->tail = newnode; //接着就是隊尾變成了剛剛進來的新結點,以此類推,下一個進來的新結點(假設為y)便是頭結點指向x,x指向y,y指向nul
}
int
notEmpty(Queue *Q) {
return
(Q->Length > 0);
}
int
DeQueue(Queue *Q,
int
*x) {
// 將x送出隊
PNode p; //定義結點指針p
if
(notEmpty(Q)) {
p = Q->head->next; // p的地址是頭指針所指的下一個地址,也就是第一個元素的地址
*x = p->data; //訪問p的地址,取該地址的數據域的數據
Q->head->next = p->next; //此時,將頭指針指向p的下一個地址,即第二個元素。下一次調用函數便是p值為第二個(y),以此類推第三個、第四個。。。直到尾指針指向空指針結束
--Q->Length; //隊列長度減一
free
(p); //釋放p的空間,此時p的地址也就是隊列里面結點的地址
return
1;
}
return
0;
}
int
GetLength(Queue *Q) {
// 獲取隊列長度
return
Q->Length;
}
int
GetFirst(Queue *Q) {
// 獲取隊頭數據
return
Q->head->next->data;
}
int
GetLast(Queue *Q) {
// 獲取隊尾數據
return
Q->tail->data;
}
void
ClearQueue(Queue *Q) {
Q->tail = Q->head;
Q->Length = 0;
}
void
DestroyQueue(Queue *Q) {
PNode q,p = Q->head;
while
(p) {
q = p;
p = q->next;
free
(q);
}
Q->head = Q->tail = NULL;
free
(Q);
Q = NULL;
}
int
main() {
int
i,n = 10,x;
Queue *Q = GetQueue();//定義一個新的隊列
srand
(
time
(0)); //用於rand()產生隨機數的前提,播種,播下time(0),那么每次運行程序得到的種子不同,產生的隨機數列也就不同。
for
(i = 0; i < n; ++i) {
x =
rand
() % 100;//產生一個不大於100的隨機數
printf
(
"%d "
,x);
EnQueue(Q,x);//x送進隊列
}
printf
(
"\n"
);
while
(notEmpty(Q)) {//判斷沒有空隊列
DeQueue(Q,&x);//出隊列
printf
(
"%d "
,x);
}
printf
(
"\n"
);
return
0;
}