数据结构 队列 queue C语言 排队 报数

循环队列的基本操作:初始化队列、判队列为空、判队列为满、出队列、入队列等运算。
该程序的功能是实现循环队列的定义和操作。

#define MAXQSIZE  100  //最大队列长度
  typedef struct
 { QElemType  *base;  // 动态分配存储空间
    int  front;     // 头指针,若队列不空,指向队列头元素
    int  rear;      // 尾指针,若队列不空,指向队列尾元素 的下一个位置
} SqQueue;

1、 构造一个空队列Q
2、 插入元素e为Q的新的队尾元素
3、 若队列不空,则删除Q的队头元素,用e返回其值,否则返回ERROR
4、 若队列不空,则取队首元素,用e返回其值
5、 判断队列是否为空
6、 判断队列是否为满
引用上述操作的应用
(1)问题描述
设有n个人排成一列,从前往后“0,1”连续报数。凡是报到“0”的人出列,凡是报到“1”的人立即站到队伍的最后。反复进行报数,直到所有人均出列为止。要求给出这n个人的出列顺序。
例如,n=5时,初始序列为1、2、3、4、5,
出队序列为1、3、5、4、2

// 循环队列.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

typedef int QElemType;
typedef int Status;

#define MAXQSIZE 100

#define OK 1
#define ERROR 0
#define OVERFLOW 0
//author: 小柳学渣
typedef struct
{
	QElemType *base;
	int front;
	int rear;
}SqQueue;
//author: 小柳学渣
/*构造*/
Status InitQueue(SqQueue &Q)
{
	Q.base = (QElemType*)malloc(MAXQSIZE * sizeof(QElemType));
	if (!Q.base)
	{
		printf("存储分配失败");
		system("pause");
		exit(OVERFLOW);
	}
	Q.front = Q.rear = 0;
	return OK;
}

/*长度*/
Status QueueLength(SqQueue &Q)
{
	return (Q.rear - Q.front + MAXQSIZE) % MAXQSIZE;
}

/*插入*/
Status EnQueue(SqQueue &Q, QElemType e)
{
	if ((Q.rear + 1) % MAXQSIZE == Q.front)
	{
		printf("队列满");
		system("pause");
		exit(OVERFLOW);
	}
	Q.base[Q.rear] = e;
	Q.rear = (Q.rear + 1) % MAXQSIZE;
	return OK;
}

/*删除*/
Status DeQueue(SqQueue &Q, QElemType &e)
{
	if (Q.front == Q.rear)
	{
		printf("队列为空");
		system("pause");
		return ERROR;
	}
	e = Q.base[Q.front];
	Q.front = (Q.front + 1) % MAXQSIZE;
	return OK;
}

/*判断是否为空*/
Status QueueEmpty(SqQueue &Q)
{
	if (Q.rear == Q.front)
		return 1;
	else
		return 0;
}

/*判断是否为满*/
Status QueueFull(SqQueue &Q)
{
	if (Q.front == (Q.rear + 1)% MAXQSIZE)
		return 1;
	else
		return 0;
}


//author: 小柳学渣
/*(1)问题描述
设有n个人排成一列,从前往后“0,1”连续报数。凡是报到“0”的人出列,凡是报到“1”的人立即站到队伍的最后。反复进行报数,直到所有人均出列为止。要求给出这n个人的出列顺序。
例如,n=5时,初始序列为1、2、3、4、5,
          出队序列为1、3、5、4、2*/
Status QueueA(SqQueue &Q)
{//author: 小柳学渣
	int x, y, n;
	printf("Input n:");
	scanf_s("%d", &n);
	for (int i = 1; i <= n; i++)
		EnQueue(Q, i);
	while (!QueueEmpty(Q))
	{
		DeQueue(Q, x);
		printf("%d ", x);
		if (!QueueEmpty(Q))
		{
			DeQueue(Q, y);
			EnQueue(Q, y);
		}
	}
    printf(“\n”);
	return OK;
}
//author: 小柳学渣
int main()
{
	SqQueue Q;
	InitQueue(Q);
	QueueA(Q);
	return 0;
}

循环队列的定义及基本操作:初始化队列、判队列为空、判队列为满、出队列、入队列等运算。

猜你喜欢

转载自blog.csdn.net/l503301397/article/details/86677160