c_cpp 单片机C编程自定义通用队列接口

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 单片机C编程自定义通用队列接口相关的知识,希望对你有一定的参考价值。

int main()
{
    AVG_Queue* queue = AVG_QueueInit(10);
    int data[11] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int i = 0;
    int *temp = NULL;

    for(i=0; i<11; i++)
    {
        AVG_QueuePushInfo(queue, data+i);
    }

    do
    {
        temp = (int*)AVG_QueuePopInfo(queue);
        if(temp == NULL)
                break;
        printf("Queue pop info:%d\n", *temp);
    }while(1);

    AVG_QueueDestory(queue);

    return 0;
}
#ifndef __AVG_QUEUE_H
#define __AVG_QUEUE_H

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

typedef struct _avg_queue_node
{
	void* info;
	struct _avg_queue_node* prev;
}AVG_QueueNode;

typedef struct _avg_queue
{
	AVG_QueueNode* head;
	AVG_QueueNode* tail;
	uint8_t size;
	uint8_t limit;
}AVG_Queue;

//队列节点初始化以及销毁
AVG_QueueNode* AVG_QueueNodeInit(void *info);
void AVG_QueueNodeDestory(AVG_QueueNode* obj);

//队列初始化以及销毁
AVG_Queue* AVG_QueueInit(uint8_t limit);
void AVG_QueueDestory(AVG_Queue* obj);

//队列节点操作
void AVG_QueuePushInfo(AVG_Queue* obj, void* info);
void* AVG_QueuePopInfo(AVG_Queue* obj);

#endif //__AVG_QUEUE_H
#include "avg_queue.h"

//队列节点初始化和销毁
AVG_QueueNode* AVG_QueueNodeInit(void *info)
{
	AVG_QueueNode* obj = (AVG_QueueNode*)malloc(sizeof(AVG_QueueNode));
	
	//队列节点申请内存失败
	if(obj == NULL)
		return NULL;
	
	obj->info = info;
	obj->prev = NULL;
	
	return obj;
}

void AVG_QueueNodeDestory(AVG_QueueNode* obj)
{
	free(obj);
}

//队列初始化和销毁
AVG_Queue* AVG_QueueInit(uint8_t limit)
{
	AVG_Queue* obj = (AVG_Queue*)malloc(sizeof(AVG_Queue));
	
	//内存申请失败
	if(obj == NULL)
		return NULL;
	
	//成员变量初始化
	obj->limit = limit;
	obj->size = 0;
	obj->head = NULL;
	obj->tail = NULL;
	
	return obj;
}
void AVG_QueueDestory(AVG_Queue* obj)
{	
	//循环释放掉队列内部的所有节点内存
	while(AVG_QueuePopInfo(obj) != NULL);
	//释放队列内存
	free(obj);
	
}

//队列操作
void AVG_QueuePushInfo(AVG_Queue* obj, void* info)
{
	//避免添加无效的信息
	if(obj==NULL || info==NULL)
		return;
	
	AVG_QueueNode* node = AVG_QueueNodeInit(info);
	
	if(obj->size >= obj->limit)
	{
		//队列大小超过限制,弃掉队列中一个节点
		AVG_QueuePopInfo(obj);
	}
	
	//添加新节点
	if(obj->size == 0)
	{
		//队列为空
		obj->head = node;
		obj->tail = node;
	}
	else
	{
		//队列不为空
		obj->tail->prev = node;
		obj->tail = node;
	}
	
	obj->size++;
}

void* AVG_QueuePopInfo(AVG_Queue* obj)
{
	AVG_QueueNode* node;
	void* info;
	
	//无效的队列或队列中无可用的节点
	if(obj==NULL || obj->size==0)
		return NULL;
	//取出队列的头节点
	node = obj->head;
	obj->head = obj->head->prev;
	obj->size--;
	//保存节点负载的信息
	info = node->info;
	//释放节点,避免内存泄漏
	AVG_QueueNodeDestory(node);
	
	return info;
}

以上是关于c_cpp 单片机C编程自定义通用队列接口的主要内容,如果未能解决你的问题,请参考以下文章

django web 自定义通用权限控制

Android 自定义通用的loadingview

WPF报表自定义通用可筛选列头-WPF特工队内部资料

2.Android 自定义通用的Item布局

WPF报表自定义通用可筛选列头-WPF特工队内部资料

LayUi创建一个自定义通用模块