岱岳区网站设计台州网站建设惠店
news/
2025/9/23 4:41:43/
文章来源:
岱岳区网站设计,台州网站建设惠店,网站建设是广告吗,莱芜又出大事https://blog.csdn.net/kxcfzyk/article/details/31728179
队列并不是很复杂的数据结构#xff0c;但是非常实用#xff0c;这里实现一个队列是因为在我的另一篇博客非常精简的Linux线程池实现中要用到。 队列API定义如下#xff1a; //queue.h #ifndef QUEUE_H_INCLUDED…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; pqueue_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.elementNULL; q-front.nextNULL; q-tailq-front; return q; } int queue_isempty(queue_t q) { return q-frontq-tail; } void* queue_enqueue(queue_t q, unsigned int bytes) { q-tail-next(struct node*)malloc(sizeof(struct node)); q-tail-next-elementmalloc(bytes); q-tail-next-nextNULL; q-tailq-tail-next; return q-tail-element; } void* queue_dequeue(queue_t q) { struct node *tmpq-front.next; void *element; if(tmpNULL) { return NULL; } elementtmp-element; q-front.nexttmp-next; free(tmp); if(q-front.nextNULL) { q-tailq-front; } return element; } void queue_destroy(queue_t q) { struct node *tmp, *pq-front.next; while(p!NULL) { tmpp; pp-next; free(tmp); } free(q); // 感谢Toudsour指正 }
应用程序使用队列时只需要包含queue.h头文件并在编译时将queue.c一起编译就行了。因为队列的声明和实现是严格分离的包含queue.h的应用程序无法也不应该通过队列指针直接访问队列结构体的成员。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/911381.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!