Queue--队列(c语言简单实现)

时间:2022-06-01 17:00:04
 1 #include<stdlib.h>
 2 typedef char ele;
 3 typedef struct node{
 4     ele e;
 5     struct node     qnode;
 6 }QNode,*Qptr;
 7 
 8 typedef struct{
 9     Qptr front;
10     Qptr rear;
11 }Queue;
12 
13 //初始化空队列
14 void initQueue(Queue *q){
15     q->front=q->rear=(QNode *)malloc(sizeof(QNode));
16     if(!q->front)exit(0);
17     q->front->qnode=NULL;
18 }
19 
20 //插入队列
21 void insert(Queue *q,ele e){
22     QNode node = (QNode *)malloc(sizeof(QNode));
23     if(!node)exit(0);
24     node->e=e;
25     node->qnode=NULL;
26     q->rear->qnode=node;
27     q->rear=node;
28 }
29 
30 //out queue
31 ele delQueue(Queue *q){
32     if(q->front==q->rear)return NULL;
33     QNode node = q->front->qnode;
34     ele e = node->e;
35     q->front->qnode=node->qnode;
36     if(q->rear==q)q->rear=q->front;
37     free(node);
38     return e;
39 }
40 
41 //clear queue
42 void clearQueue(Queue *q){
43     if(q->front==q->rear)return ;
44     while(q->front!=q->rear){
45         QNode node = q->front->qnode;
46         q->front->qnode = node->qnode;
47         free(node);
48     }
49 }