头文件
1 #ifndef QUEUE_H
2 #define QUEUE_H
3 typedef int data_t
4 typedef struct queue
5 {
6 data_t *que;
7 int head;
8 int tail;
9 int tlen;
10 }queue_t;
11 #endif
队列的创建
1 queue_t* queue_create(int len)
2 {
if(len<2)
return NULL;
3 queue_t*pq=malloc(sizeof(queue_t));
4 if(pq==NULL)
5 return NULL;
6 pq->que=malloc(sizeof(data_t)*len);
7 if(pq->que==NULL)
8 {
9 free(pq);
10 return NULL;
11 }
12 pq->head=0;
13 pq->tail=0;
14 pq->tlen=len;
15 return pq;
16 }
整个队列放在一个结构体中,最大容量在创建时就被规定,需要注意,队列长度为0或1时队列无意义,不创建(并且长度为1时head始终等于tail,无法入队或者出队)
判断队列是否为满--是否为空
18 int is_full(queue_t *pque)
19 {
20 if((pque->tail+1)%pque->tlen==pque->head)
21 return 1;
22 return 0;
23 }
24
25 int is_empty(queue_t *pque)
26 {
27 return pque->tail == pque->head;
28 }
入队
30 int enqueue(queue_t *pque,data_t data)
31 {
32 if(is_full(pque))
33 return -1;
34 pque->que[pque->tail]=data;
35 pque->tail=(pque->tail+1)%pque->tlen;
36 return 0;
37 }
先判断队列是否为满,不满则在尾部入队,尾下标后移,注意数组是否越界
出队
39 int dequeue(queue_t *pq,data_t *data)
40 {
41 if(is_empty(pq))
42 return -1;
43 *data=pq->que[pq->head];
44 pq->head=(pq->head+1)%pq->tlen;
45 return 0;
46 }
判断队列是否为空,用指针拿走数据并头删
销毁队列
48 void queue_destroy(queue_t **pq)
49 {
50 if(pq==NULL || *pq==NULL)
51 return;
52 free((*pq)->que);
53 free(*pq);
54 *pq=NULL;
55 return ;
56 }
需要用二级指针带入结构体,用二级指针才能把主调函数中的一级指针置空
用链表也可以构成队列,只需要创建、头插、尾删(指针带出数据)、销毁
与链表队列类似,栈链表只需要创建、头插、头删(指针带出数据)、销毁