C语言循环队列

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

#define MAX_QSIZE 5
#define OVERFLOW 0
#define TRUE 1
#define FALSE 0
#define ERROR -1
#define OK 0

typedef int QElemType;
typedef int Status;

struct SqQueue
{
	QElemType *base;
	int front;
	int rear;
};

void InitQueue(SqQueue &Q)
{
	Q.base = (QElemType *)malloc(sizeof(QElemType));
	if(!Q.base)
		exit(OVERFLOW);
	Q.front = Q.rear = 0;
}

void DestroyQueue(SqQueue &Q)
{
	if(Q.base)
		free(Q.base);
	Q.base = NULL;
	Q.front = Q.rear = 0;
}

void ClearQueue(SqQueue &Q)
{
	Q.front = Q.rear = 0;
}

Status QueueEmpty(SqQueue Q)
{
	if (Q.front == Q.rear)
	{
		return TRUE;
	} 
	else
	{
		return FALSE;
	}
}

Status QueueFull(SqQueue Q)
{
	if ((Q.rear + 1) % MAX_QSIZE == Q.front)
	{
		return TRUE;
	} 
	else
	{
		return FALSE;
	}
}

Status GetHead(SqQueue Q, QElemType &e)
{
	if (QueueEmpty(Q))
	{
		return ERROR;
	}
	e = Q.base[Q.front];

	return OK;
}

Status EnQueue(SqQueue &Q, QElemType e)
{
	if(QueueFull(Q))
		return ERROR;
	Q.base[Q.rear] = e;
	Q.rear = (Q.rear + 1) % MAX_QSIZE;

	return OK;
}

int QueueLength(SqQueue Q)
{
	return (Q.rear - Q.front + MAX_QSIZE) % MAX_QSIZE;
}


Status DeQueue(SqQueue &Q, QElemType &e)
{
	if(QueueEmpty(Q))
		return ERROR;
	e = Q.base[Q.front];
	Q.front = (Q.front + 1) % MAX_QSIZE;

	return OK;
}

void print(QElemType e)
{
	printf("%d ", e);
}

void QueueTraverse(SqQueue Q, void(*visit)(QElemType))
{
	int i = Q.front;
	while(i != Q.rear)
	{
		visit(Q.base[i]);
		i = (i + 1) % MAX_QSIZE;
	}
	printf("\n");
}

int main()
{
	Status j;
	QElemType d;

	SqQueue Q;
	InitQueue(Q);

	EnQueue(Q, 1);
	if(QueueFull(Q))
		printf("Full\n");
	else
		printf("not Full\n");

	EnQueue(Q, 2);
	EnQueue(Q, 3);
	EnQueue(Q, 4);
	EnQueue(Q, 5);//ERROR
	
	QueueTraverse(Q, print);
	if(QueueFull(Q))
		printf("Full\n");
	else
		printf("not Full\n");

	DeQueue(Q, d);
	printf("%d\n", d);
	QueueTraverse(Q, print);

	GetHead(Q, d);
	printf("%d\n", d);
	QueueTraverse(Q, print);

	int len = QueueLength(Q);
	printf("Length = %d\n", len);

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值