`
kerrysk
  • 浏览: 16909 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

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;
	}
}



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics