其他分享
首页 > 其他分享> > 严蔚敏C语言版数据结构之循环队列的基本操作

严蔚敏C语言版数据结构之循环队列的基本操作

作者:互联网

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

#define ok 1
#define error 0
#define maxsize 90//最大队列长度

typedef int status;
typedef int qelemtype;

typedef struct{
	qelemtype *base;
	int front;
	int rear;
}sqqueue;

status initqueue(sqqueue &q)//构造一个空队列
{
	q.base = (qelemtype*)malloc(maxsize*sizeof(qelemtype));
	if (!q.base)
		return error;
	q.front = q.rear = 0;
	return ok;
}

void queuelength(sqqueue q)//求队列的长度
{
	int len = (q.rear - q.front) % maxsize;
	printf("此时循环队列的长度为:%d\n", len);
}

status enqueue(sqqueue &q, qelemtype e)//插入元素e为q的新的队尾元素
{
	if ((q.rear + 1) % maxsize == q.front)
		return error;//队列满
	q.base[q.rear] = e;
	q.rear = (q.rear + 1) % maxsize;//队尾+1,但此时的q.rear还是随机值
	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)//输出队列中的元素
{
	printf("此时的队列状态为:");
	while (q.front <q.rear)//队列中的元素从q.front~q.rear-1;
	{
		printf("%4d", q.base[q.front]);
		q.front++;
	}
	printf("\n");
	return ok;
}

status gethead(sqqueue q, qelemtype &e)//取队头元素
{
	if (q.front == q.rear)
		return error;
	e = q.base[q.front];
	return ok;
}

status clearqueue(sqqueue &q)//清空队列
{
	q.front = q.rear;
	return ok;
}

status destoryqueue(sqqueue &q)//销毁队列
{
	free(q.base);
	return ok;
}

status queueempty(sqqueue q)//队列判空
{
	if (q.front == q.rear)
		return ok;
	else
		return error;
}

int main()
{
	sqqueue q;
	qelemtype e;
	int i;
	if (initqueue(q) == ok)
		printf("队列创建成功!\n");
	else
		printf("队列创建失败!\n");
	for (i = 1; i <= 5; i++)
		enqueue(q, i*2);
	queuetraverse(q);
	queuelength(q);
	printf("将20插入到队列中\n");
	enqueue(q, 20);
	queuetraverse(q);
	queuelength(q);
	printf("队头元素出队列\n");
	dequeue(q, e);
	queuetraverse(q);
	printf("出队列的元素是:%d\n", e);
	gethead(q, e);
	printf("新的队头元素为:%d\n", e);
	if (queueempty(q) == ok)
		printf("队列为空!\n");
	else
		printf("队列不为空!\n");
	if (clearqueue(q) == ok)
		printf("置空成功!\n");
	destoryqueue(q);
	system("pause");
	return ok;

}

标签:return,队列,sqqueue,C语言,maxsize,严蔚敏,front,基本操作,rear
来源: https://blog.csdn.net/m0_46297137/article/details/104701664