一个通用纯C队列的实现
https://blog.csdn.net/kxcfzyk/article/details/31728179
隊列并不是很復(fù)雜的數(shù)據(jù)結(jié)構(gòu),但是非常實用,這里實現(xiàn)一個隊列是因為在我的另一篇博客非常精簡的Linux線程池實現(xiàn)中要用到。
?
隊列API定義如下:
?
//queue.h
#ifndef QUEUE_H_INCLUDED
#define QUEUE_H_INCLUDED
typedef struct queue *queue_t;
queue_t queue_create();
int queue_isempty(queue_t q);
void* queue_enqueue(queue_t q, unsigned int bytes);
void* queue_dequeue(queue_t q);
void queue_destroy(queue_t q);
#endif //QUEUE_H_INCLUDED
隊列API提供的功能有:創(chuàng)建隊列,判斷隊列是否為空,入隊,出隊,銷毀隊列。這個隊列是通用的,不針對特定數(shù)據(jù)類型,它里面存儲的元素是void*類型的指針。注意這個隊列跟普通隊列的入隊操作有所不同。普通隊列的入隊操作通常如下:
?
struct type *p;
p = malloc(sizeof(struct type));
p->a = ...;
p->b = ...;
p->c = ...;
...
queue_enqueue(q, p);
而這里的入隊操作簡化了流程:
?
struct type *p;
p=queue_enqueue(q, sizeof(struct type));
p->a = ...;
p->b = ...;
p->c = ...;
...
另外雖然隊列元素(指針)所指向的內(nèi)存空間是在入隊操作時由隊列分配的,但是隊列元素出隊以后,隊列并不負(fù)責(zé)元素所指向內(nèi)存空間的釋放,隊列使用者應(yīng)該自己手動釋放內(nèi)存。
?
隊列的實現(xiàn)如下:
?
//queue.c
#include "queue.h"
#include <stdlib.h>
struct node {
void *element;
struct node *next;
};
struct queue {
struct node front;
struct node *tail;
};
queue_t queue_create() {
queue_t q;
q=(queue_t)malloc(sizeof(struct queue));
q->front.element=NULL;
q->front.next=NULL;
q->tail=&q->front;
return q;
}
int queue_isempty(queue_t q) {
return &q->front==q->tail;
}
void* queue_enqueue(queue_t q, unsigned int bytes) {
q->tail->next=(struct node*)malloc(sizeof(struct node));
q->tail->next->element=malloc(bytes);
q->tail->next->next=NULL;
q->tail=q->tail->next;
return q->tail->element;
}
void* queue_dequeue(queue_t q) {
struct node *tmp=q->front.next;
void *element;
if(tmp==NULL) {
return NULL;
}
element=tmp->element;
q->front.next=tmp->next;
free(tmp);
if(q->front.next==NULL) {
q->tail=&q->front;
}
return element;
}
void queue_destroy(queue_t q) {
struct node *tmp, *p=q->front.next;
while(p!=NULL) {
tmp=p;
p=p->next;
free(tmp);
}
free(q); // 感謝@Toudsour指正
}
應(yīng)用程序使用隊列時只需要包含queue.h頭文件,并在編譯時將queue.c一起編譯就行了。因為隊列的聲明和實現(xiàn)是嚴(yán)格分離的,包含queue.h的應(yīng)用程序無法也不應(yīng)該通過隊列指針直接訪問隊列結(jié)構(gòu)體的成員。
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的一个通用纯C队列的实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 丛林笔记剧情介绍
- 下一篇: 循环服务器,并发服务器模型以及I/O多路