データ構造C言語実装—キュー操作
17020 ワード
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 typedef int elemType;
5 /************************************************************************/
6 /* 6 */
7 /************************************************************************/
8
9 struct sNode{
10 elemType data; /* */
11 struct sNode *next; /* */
12 };
13
14 struct queueLK{
15 struct sNode *front; /* */
16 struct sNode *rear; /* */
17 };
18
19 /* 1. */
20 void initQueue(struct queueLK *hq)
21 {
22 hq->front = hq->rear = NULL; /* */
23 return;
24 }
25
26 /* 2. x */
27 void enQueue(struct queueLK *hq, elemType x)
28 {
29 /* newP */
30 struct sNode *newP;
31 newP = malloc(sizeof(struct sNode));
32 if(newP == NULL){
33 printf(" ! ");
34 exit( 1 );
35 }
36
37 /* x , */
38 newP->data = x;
39 newP->next = NULL;
40
41 /* , */
42 if(hq->rear == NULL){
43 hq->front = hq->rear = newP;
44 }else {
45 /* , , */
46 hq->rear = hq->rear->next = newP; /* */
47 }
48 return;
49 }
50
51 /* 3. */
52 elemType outQueue(struct queueLK *hq)
53 {
54 struct sNode *p;
55 elemType temp;
56
57 /* */
58 if(hq->front == NULL){
59 printf(" , ! ");
60 exit(1);
61 }
62 temp = hq->front->data; /* */
63 p = hq->front; /* */
64 hq->front = p->next; /* */
65
66 /* , */
67 if (hq->front == NULL){
68 hq->rear = NULL;
69 }
70
71 free(p); /* */
72 return temp; /* */
73 }
74
75 /* 4. */
76 elemType peekQueue(struct queueLK *hq)
77 {
78 /* */
79 if(hq->front == NULL){
80 printf(" , ! ");
81 exit(1);
82 }
83
84 return hq->front->data; /* */
85 }
86
87 /* 5. , 1, 0 */
88 int emptyQueue(struct queueLK *hq)
89 {
90 /* */
91 if(hq->front == NULL){
92 return 1;
93 }else{
94 return 0;
95 }
96 }
97
98 /* 6. */
99 void clearQueue(struct queueLK *hq)
100 {
101 struct sNode *p = hq->front; /* p */
102 /* , */
103 while(p != NULL){
104 hq->front = hq->front->next;
105 free(p);
106 p = hq->front;
107 } /* */
108
109 hq->rear = NULL; /* */
110 return;
111 }
112
113 /************************************************************************/
114
115 int main(int argc, char* argv[])
116 {
117 struct queueLK q;
118 int a[8] = {3, 8, 5, 17, 9, 30, 15, 22};
119 int i;
120
121 initQueue(&q);
122 for(i = 0; i < 8; i ){
123 enQueue(&q, a[i]);
124 }
125 printf("%d ", outQueue(&q));
126 printf("%d ", outQueue(&q));
127
128 enQueue(&q, 68);
129 printf("%d ", peekQueue(&q));
130 printf("%d ", outQueue(&q));
131
132 while(!emptyQueue(&q)){
133 printf("%d ", outQueue(&q));
134 }
135
136 printf("");
137 clearQueue( &q);
138 system("pause");
139
140 return 0;
141 }