顺序循环队列基本操作(入队,出队,清空,销毁,历遍)

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

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

typedef int QElemType;
typedef int Status;


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

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

Status DestoryQueue(SqQueue &Q)
{
	if(Q.base)
		free(Q.base);
	Q.base = NULL;
	Q.front = Q.rear = 0;
	return OK;
}

Status ClearQueue(SqQueue &Q)
{
	Q.front = Q.rear = 0;	
	return OK;
}

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

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

Status GetHead(SqQueue Q, QElemType &d)
{
	if(Q.front == Q.rear) return ERROR;
	d = *(Q.base + Q.front);
	return OK;
}

Status EnQueue(SqQueue &Q,QElemType e)
{
	if((Q.rear + 1)%MAXSIZE == Q.front)
		return TRUE;
	Q.base[Q.rear] = e;
	Q.rear = (Q.rear + 1)%MAXSIZE;
	return OK;
}

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

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

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

int main()
{
	int i = 0,l;
	Status j;
	QElemType d;
	SqQueue Q;
	InitQueue(Q);
	printf("After init queue,is it empty?%d(1:YES 0:NO)\n",QueueEmpty(Q));
	printf("Please input int type queue (length is less than %d), -1 is end character:\n",MAXSIZE - 1);

	do
	{
		scanf("%d",&d);
		++i;
		if(d == -1)
			break;
		EnQueue(Q,d);
	}while(i < MAXSIZE -1);
	printf("The length of queue is:%d\n",QueueLength(Q));
	printf("Is it empty?%d(1:YES 0:NO)\n",QueueEmpty(Q));
	printf("Delete element % times from the head of queue, insert element at the end of queue:\n",MAXSIZE);
	
	for(i = 0; i < MAXSIZE; ++i)
	{
		DeQueue(Q,d);
		printf("The deleted element is %d,please input the new element:\n",d);
		scanf("%d",&d);
		EnQueue(Q,d);
	}
	l = QueueLength(Q);
	printf("The elements of queue are:\n");
	QueueTraverse(Q,visit);
	printf("the number of inserted data at end of queue is:%d\n", i+MAXSIZE);
	if(l - 2 > 0)
		printf("delete %d elements:\n",l-2);
	while(QueueLength(Q) > 2)
	{
		DeQueue(Q,d);
		printf("the deleted element is:%d\n",d);
	}
	j = GetHead(Q,d);
	if(j)
		printf("the head element is:%d\n",d);
	ClearQueue(Q);
	printf("After clear queue,is it empty?(1:YES 0:NO)\n",QueueEmpty(Q));
	DestoryQueue(Q);
	return 0;
}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值