数据结构之队列

源文件部分

#include <stdio.h>
#include <stdint.h>
#include "queue.h"
#define Q_DIM(array_) (sizeof(array_) / sizeof(array_[0]))
typedef unsigned int bool;

uint32_t MyEvtPoolSto[5];
Queue_ MyQueue;

int Queue_int(Queue_ * me, uint32_t *qSto[], uint_fast16_t qLen)
{
	me->uiFornt = 0; 
	me->ring = &qSto[0]; 
	me->end = (uint_fast16_t)qLen;
	if (qLen != (uint_fast16_t)0) {
		me->head = (uint_fast16_t)0;
		me->tail = (uint_fast16_t)0;
	}
	me->nFree = (uint_fast16_t)(qLen + (uint_fast16_t)1);
	return 0;
}

bool MyQueue_post_FIFO(Queue_ * const me, uint32_t Maruko)
{
	bool bState = 1;
	if (me->nFree > 0)
	{
		me->nFree--;
		if (me->uiFornt == 0)
		{
			me->uiFornt = Maruko;
		}
		else
		{
			me->ring[me->head] = Maruko;
			if (me->head == 0)
			{
				me->head = me->end;
			}
			me->head--;

		}
		bState = 1;
	}
	else
	{
		bState = 0;
	}
	return bState;
}

uint32_t MyQueue_get(Queue_ * me)
{
	uint32_t Maruko;
	Maruko = me->uiFornt;
	if (Maruko != 0)
	{
		me->nFree++;
		if (me->nFree <= me->end)/* any events in the ring buffer? */
		{
			me->uiFornt = me->ring[me->tail];
			me->ring[me->tail] = 0;
			if (me->tail == 0)
			{
				me->tail = me->end;
			}
			--me->tail;
		}
		else
		{
			me->uiFornt = 0;
		}
	}
	return Maruko;
}

int main(void)
{
	int iKey1;
	int iKey2;
	uint32_t uiPara = 0;
	bool bIsEmpty;

	Queue_int(&MyQueue, MyEvtPoolSto, Q_DIM(MyEvtPoolSto));

	while (1)
	{
		scanf_s("%d", &iKey1);

		if (iKey1 == 11)
		{
			printf("请输入事件信号:");
			scanf_s("%d", &iKey2);
			bIsEmpty = MyQueue_post_FIFO(&MyQueue, iKey2);
			if (bIsEmpty == 0)
			{
				printf("队列已满\n");
			}
		}
		else if (iKey1 == 12)
		{
			uiPara = MyQueue_get(&MyQueue);
			if (uiPara != 0)
			{
				printf("取出的事件信号为%d\n", uiPara);
			}
			else
			{
				printf("队列内事件为空");
			}
		}
	}
	return 0;
}


头文件部分

#pragma once
#include <stdio.h>
#include <stdint.h>


#ifndef QUEUE_H
#define QUEUE_H


typedef struct Queue_tag
{
	uint32_t  uiFornt;

	uint32_t  *ring;

	uint32_t end;

	uint32_t volatile head;

	uint32_t volatile tail;

	uint32_t volatile nFree;
}Queue_;


#endif

输出结果

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值