C 实现循环队列

前几天在公司开发写了个循环队列,感觉挺好的,没用上可惜了。拿出来秀一秀

 队列可以自动增长,就是涨上去需要再trim下。

 

头文件:

 

#ifndef _NODECIRCLEQUEUE_H
#define _NODECIRCLEQUEUE_H

typedef enum { false=0, true=!false } bool;

typedef void *Node;

typedef struct NodeCircleQueue_T{
	Node	*queue;
	int	head;
	int	tail;
	int	initLength;
	int	maxLength;
}NodeCircleQueue;

typedef void (*NodeFunc) (Node node,void *args);

bool vInitNodeCircleQueue(NodeCircleQueue *cqueue,int initLength,int maxLength);

void vDestoryNodeCircleQueue(NodeCircleQueue *cqueue);

bool vOfferNodeCircleQueue(NodeCircleQueue *cqueue,Node node);

Node vPollNodeCircleQueue(NodeCircleQueue *cqueue);

void vTraversalNodeCircleQueue(NodeCircleQueue *cqueue,NodeFunc func,void *args);

#endif

源文件:

 #include "nodeCircleQueue.h"

#include <stdlib.h>
#include <string.h>

bool vInitNodeCircleQueue(NodeCircleQueue *cqueue,int initLength,int maxLength){
	cqueue->queue = (Node*)malloc(initLength * sizeof(Node));
	if(cqueue->queue == NULL){
		return false;	
	}
	cqueue->head = cqueue->tail = 0;
	cqueue->initLength = initLength;
	cqueue->maxLength = maxLength;
	return true;
}

void vDestoryNodeCircleQueue(NodeCircleQueue *cqueue){
	free(cqueue->queue);
}

bool vOfferNodeCircleQueue(NodeCircleQueue *cqueue,Node node){
	//queue is full
	if(cqueue->head == ((cqueue->tail+1) % cqueue->initLength)){
		if(cqueue->initLength == cqueue->maxLength)
			return false;

		Node* newQueue;
		int newLength;
		
		newLength = cqueue->initLength * 2;
		if(newLength > cqueue->maxLength)
			newLength = cqueue->maxLength;

		newQueue = (Node*)malloc(newLength * sizeof(Node));
		if(newQueue == NULL)
			return false;
		memcpy(newQueue , cqueue->queue , cqueue->initLength * sizeof(Node));
		free(cqueue->queue);

		cqueue->initLength = newLength;
		cqueue->queue = newQueue;
	}
	//put node at tail,tail++
	*(cqueue->queue + cqueue->tail) = node;
	cqueue->tail = (cqueue->tail + 1) % cqueue->initLength;
	return true;
}

Node vPollNodeCircleQueue(NodeCircleQueue *cqueue){
	//queue is empty
	if(cqueue->tail == cqueue->head)
		return NULL;
	Node node;
	//node = head, head++
	node = *(cqueue->queue + cqueue->head);
	cqueue->head = (cqueue->head + 1) % cqueue->initLength;
	return node;
}

void vTraversalNodeCircleQueue(NodeCircleQueue *cqueue,NodeFunc func,void *args){
	int ptr;
	
	ptr = cqueue->head;
	while(ptr != cqueue->tail){
		func(*(cqueue->queue + ptr),args);
		ptr = (ptr + 1)% cqueue->initLength;
	}
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值