循环队列-顺序存储结构-数据结构

循环队列采用顺序存储结构,

简单的基本操作,入队,出队,取对头元素,判断是否空队列,队列长度

例代码:

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

#define ERROR 0
#define OK 1
#define OVERFLOW -1
#define MAXSIZE 10


typedef int Elemtype;
typedef int Status;

typedef struct SqQue
{
	Elemtype *base;
	int front;
	int rear;
}SqQue;

Status InitQue(SqQue &q)  //initialize the queue
{
	q.base=(Elemtype*)malloc(MAXSIZE*sizeof(Elemtype));
	if(!q.base) exit(OVERFLOW);
	q.front=q.rear=0;
	return OK;
}

bool EmptyQue(SqQue q)   //if empty
{
	if(q.front==q.rear) return true;
	else return false;
}

Status EnQue(SqQue &q,Elemtype e)
{
	if((q.rear+1)%MAXSIZE==q.front) return ERROR;  //queue full
	q.base[q.rear]=e;
	q.rear=(q.rear+1)%MAXSIZE;
	return OK;
}

Status DisplayQue(SqQue q)
{
	int i;
	if(EmptyQue(q)) printf("The queue is empty!\n");
	else
	{
		i=q.front;
		while(i!=q.rear)
		{
			printf("%d ",q.base[i]);
			i=(i+1)%MAXSIZE;
		}
		printf("\n");
		return OK;
	} 
}

int QueLength(SqQue q)
{
	return (q.rear-q.front+MAXSIZE)%MAXSIZE;
}

Status DeQue(SqQue &q)
{
	Elemtype e;
	if(EmptyQue(q)) return ERROR;
	e=q.base[q.front];
	q.front=(q.front+1)%MAXSIZE;
	return OK;
}

Status GetQueHead(SqQue q,Elemtype &e)
{
	if(EmptyQue(q)) return ERROR;  //queue empty
	e=q.base[q.front];
	return OK;
}

int main()
{
	SqQue que;
	int n,i,len;
	Elemtype e;
	InitQue(que);
	if(EmptyQue(que)) printf("The initial queue is empty.\n");
	printf("Input the number of queue n(don't greater than MAXSIZE):");
	scanf("%d",&n);
	for(i=0;i<n;i++)
	{
		scanf("%d",&e);
		EnQue(que,e);
	}
	printf("After enqueue,the queue list:\n");
	DisplayQue(que);
	len=QueLength(que);
	printf("The lenght of the queue is %d.\n",len);
	GetQueHead(que,e);
	printf("The head elem of the queue is %d.\n",e);
	printf("Delete front elem\n");
	DeQue(que);
	printf("After delete front elem,the queue list:\n");
	DisplayQue(que);
	len=QueLength(que);
	printf("The lenght of the queue is %d.\n",len);	
	GetQueHead(que,e);
	printf("The head elem of the queue is %d.\n",e);
	
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值