数据结构 链队列基本操作

时间:2020-12-21 10:20:29

 

  1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <math.h>
4
5 #define OK 1
6 #define ERROR 0
7
8 typedef int QElemType;
9 typedef int Status;
10
11 typedef struct QNode
12 {
13 QElemType data;
14 struct QNode *next;
15 }QNode,*QueuePtr;
16
17 typedef struct
18 {
19 QueuePtr front,rear;
20 }LinkQueue;
21
22 Status InitQueue(LinkQueue *Q)
23 {
24 (*Q).front=(*Q).rear=(QueuePtr)malloc(sizeof(QNode));
25 if (!(*Q).front)
26 exit(OVERFLOW);
27 (*Q).front->next=NULL;
28 return OK;
29 }
30
31 Status DestroyQueue(LinkQueue *Q)
32 {
33 while ((*Q).front)
34 {
35 (*Q).rear = (*Q).front->next;
36 free((*Q).front);
37 (*Q).front = (*Q).rear;
38 }
39 return OK;
40 }
41
42 Status ClearQueue(LinkQueue *Q)
43 {
44 QueuePtr p,q;
45 (*Q).rear = (*Q).front;
46 p = (*Q).front->next;
47 (*Q).front->next=NULL;
48 while (p)
49 {
50 q = p;
51 p = p->next;
52 free(q);
53 }
54 return OK;
55 }
56
57 Status QueueEmpty(LinkQueue Q)
58 {
59 if (Q.front == Q.rear)
60 return OK;
61 else
62 return ERROR;
63 }
64
65 int QueueLength(LinkQueue Q)
66 {
67 int i=0;
68 QueuePtr p;
69 p = Q.front;
70 while (Q.rear != p)
71 {
72 i++;
73 p = p->next;
74 }
75 return i;
76 }
77
78 Status GetHead(LinkQueue Q,QElemType *e)
79 {
80 QueuePtr p;
81 if (Q.front == Q.rear)
82 return ERROR;
83 p = Q.front->next;
84 *e = p->data;
85 return OK;
86 }
87
88 Status EnQueue(LinkQueue *Q,QElemType e)
89 {
90 QueuePtr p=(QueuePtr)malloc(sizeof(QNode));
91 if(!p)
92 exit(OVERFLOW);
93 p->data=e;
94 p->next=NULL;
95 (*Q).rear->next=p;
96 (*Q).rear = p;
97 return OK;
98 }
99
100 Status DeQueue(LinkQueue *Q,QElemType *e)
101 {
102 QueuePtr p;
103 if ((*Q).front == (*Q).rear)
104 return ERROR;
105 p = (*Q).front->next;
106 *e = p->data;
107 (*Q).front->next=p->next;
108 if((*Q).rear==p)
109 (*Q).rear = (*Q).front;
110 free(p);
111 return OK;
112 }
113
114 Status QueueTraverse(LinkQueue Q,void(*vi)(QElemType))
115 {
116 QueuePtr p;
117 p = Q.front->next;
118 while (p)
119 {
120 vi(p->data);
121 p = p->next;
122 }
123 printf("\n");
124 return OK;
125 }
126
127 void visit(QElemType i)
128 {
129 printf("%d ",i);
130 }
131
132 void main()
133 {
134
135 LinkQueue Q;
136 QElemType e;
137 if( InitQueue(&Q) )
138 printf("成功创建了一个空队列!\n");
139 printf("是否为空队列?%d(1:空 0:否)",QueueEmpty(Q));
140 printf("队列长度为%d\n",QueueLength(Q));
141 EnQueue(&Q,1);
142 EnQueue(&Q,2);
143 EnQueue(&Q,3);
144 printf("插入3个元素后,队列长度为%d\n",QueueLength(Q));
145 printf("是否为空队列?%d(1:空 0:否)",QueueEmpty(Q));
146 printf("队列元素依次为:");
147 QueueTraverse(Q,visit);
148 if(GetHead(Q,&e))
149 printf("队头元素是:%d\n",e);
150 ClearQueue(&Q);
151 printf("清空队列后,Q.front=%u,Q.rear=%u,Q.front->next=%u\n",Q.front,Q.rear,Q.front->next);
152 DestroyQueue(&Q);
153 printf("清空队列后,Q.front=%u,Q.rear=%u\n",Q.front,Q.rear);
154 }