循环队列

循环队列是使用得比较多的一种数据结构.关于循环队列的实现,有两件事要警惕.第一是检测队列是否为空,满的状态很重要.
第二某些程序设计人员使用不同的方法表示队列的队头和队尾.队列的大小是通过比较尾Rear和头Front隐式算出的.这是一种非常隐秘的
方法,因为存在某些特殊情形,因此如果你要修改这种方式编写的代码就要特别的仔细.下面是循环队列用数组方式的实现.
为了区分队列为空和为满这两种情况,定义了
循环队列为空:Rear与Front相差一个数组下标  ==> (Rear + 1)%N == Front 时为空,N为队列的长度

循环队列为满:Rear与Front相差两个数组下标  ==> (Rear + 2)%N == Front 时为满,N为队列的长度


/* _Queue_h*/
#ifndef _Queue_h
#define _Queue_h
struct QueueRecord;
typedef struct QueueRecord *Queue;
typedef int ElementType;
int IsEmpty(Queue Q);
int IsFull(Queue);
Queue CreateQueue(int MaxElements);
void DisposeQueue(Queue Q);
void MakeEmpty(Queue Q);
void EnQueue(ElementType X, Queue Q);
ElementType Front(Queue Q);
void Dequeue(Queue Q);
ElementType FrontAndDequeue(Queue Q);

#endif   

/* _Queue_c*/
#include<stdio.h>
#include"queue.h"
#include<malloc.h>
#include"error.h"
struct 	QueueRecord
{
	int Capacity;
	int Front;
	int Rear;
	int Size;
	ElementType *Array;
};


int IsEmpty(Queue Q)
{
	return (Q->Rear + 1) % Q->Capacity == Q->Front;
}

int IsFull(Queue Q)
{
	return (Q->Rear + 2)% Q->Capacity == Q->Front;
}

Queue CreateQueue(int MaxElements)
{
	Queue Q	 = (Queue)malloc(sizeof(struct QueueRecord));
	if(Q == NULL)
		FatalError("Out of space!!");
	Q->Array = (ElementType *)malloc(sizeof(struct QueueRecord) * MaxElements);
	if(Q->Array == NULL)
		FatalError("Out of space!");
	Q->Capacity = MaxElements;
	MakeEmpty(Q);
	return Q;
}

void DisposeQueue(Queue Q)
{
	if(Q != NULL)
	{
		free(Q->Array);
		free(Q);
	}
}
void MakeEmpty(Queue Q)
{
	Q->Size = 0;
	Q->Rear = 0;
	Q->Front = 1;
}

void EnQueue(ElementType X, Queue Q)
{
	if(IsFull(Q))
		Error("Full queue");
	else
	{
		Q->Size ++;
		if( ++ Q->Rear == Q->Capacity )
			Q->Rear = 0;
		Q->Array[Q->Rear] = X;
	}
}

ElementType Front(Queue Q)
{
	if(!IsEmpty(Q))
		return Q->Array[Q->Front];	
	Error("Queue is empty");
	return 0;
}
void Dequeue(Queue Q)
{
	if(IsEmpty(Q))
		Error("queue is empty");
	else
	{
		Q->Size --;
		if(++ Q->Front == Q->Capacity)
			Q->Front = 0;
	}
}
ElementType FrontAndDequeue(Queue Q)
{
	ElementType ret;
	if(!IsEmpty(Q))
	{
		Q->Size --;
		ret = Q->Array[Q->Front];
		if(++ Q->Front == Q->Capacity)
			Q->Front = 0;
		return ret;
	}
	Error("queue is empty");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值