https://blog.csdn.net/kxcfzyk/article/details/31728179
隊列并不是很復雜的數據結構,但是非常實用,這里實現一個隊列是因為在我的另一篇博客非常精簡的Linux線程池實現中要用到。
?
隊列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提供的功能有:創建隊列,判斷隊列是否為空,入隊,出隊,銷毀隊列。這個隊列是通用的,不針對特定數據類型,它里面存儲的元素是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 = ...;
-
...
另外雖然隊列元素(指針)所指向的內存空間是在入隊操作時由隊列分配的,但是隊列元素出隊以后,隊列并不負責元素所指向內存空間的釋放,隊列使用者應該自己手動釋放內存。
?
隊列的實現如下:
?
-
//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指正
-
}
應用程序使用隊列時只需要包含queue.h頭文件,并在編譯時將queue.c一起編譯就行了。因為隊列的聲明和實現是嚴格分離的,包含queue.h的應用程序無法也不應該通過隊列指針直接訪問隊列結構體的成員。