1 #include <stdio.h>
2 #include <stdlib.h>
3
4 // 链队列结构体
5 typedef struct Queue
6 {
7 int data;
8 struct Queue *next;
9 } Queue, *QList;
10 // 队列指针结构体
11 typedef struct QLink
12 {
13 QList head, tail;
14 } QLink, *Q;
15 // 队列初始化
16 void init(Q &queue)
17 {
18 queue = (QLink*)malloc(sizeof(QLink));
19 queue->head = (Queue *)malloc(sizeof(Queue));
20 queue->head->next = NULL;
21 queue->tail = queue->head;
22 }
23 // 入队
24 bool enQueue(Q queue, int e)
25 {
26 //if无剩余可分配内存, 返回false
27 QList q = (Queue *)malloc(sizeof(Queue));
28 q->data = e;
29 q->next = NULL;
30 queue->tail->next = q;
31 queue->tail = queue->tail->next;
32 return true;
33 }
34 // 出队
35 bool outQueue(Q queue, int &e)
36 {
37 if (queue->head->next == NULL)
38 return false;
39 QList q = queue->head->next;
40 e = q->data;
41 queue->head = queue->head->next;
42 free(q);
43 if (queue->head->next == NULL)
44 queue->tail = queue->head;
45 return true;
46 }
47 // 判空
48 bool empty(Q queue)
49 {
50 if (queue->head == queue->tail && queue->head->next == NULL)
51 return true;
52 return false;
53 }
54 // 遍历打印
55 void print(Q queue)
56 {
57 QList q = queue->head->next;
58 while (q)
59 {
60 printf("%d ", q->data);
61 q = q->next;
62 }
63 printf("\n");
64 }
65 int main()
66 {
67 Q queue;
68 init(queue);
69 int x;
70 printf("队列是否为空, %d\n", empty(queue));
71 printf("是否可以进行出队操作, %d\n", outQueue(queue, x));
72 enQueue(queue, 10);
73 enQueue(queue, 9);
74 enQueue(queue, 8);
75 enQueue(queue, 7);
76 enQueue(queue, 6);
77 print(queue);
78 if(outQueue(queue, x))
79 {
80 printf("x is %d\n", x);
81 }
82 return 0;
83 }