队列的实际应用和操作(顺序表)

         题目:利用队列求解报数问题。设有n个人站成一排,从左向右的编号分别为1~n,现在从左往右报数“1,2,1,2,…”,数到“1”的人出列,数到“2”的立即站到队伍的最右端。报数过程反复进行,直到n个人都出列为止。要求给出他们的出列顺序。

头文件SqQueue.h

#include 
#include

#define MaxSize 100

typedef int ElemType;
typedef struct
{
	ElemType data[MaxSize];
	int front, rear;
}SqQueue;


//初始化队列运算
void InitQueue(SqQueue & sq)
{
	sq.rear = sq.front = 0;
}

//销毁队列
void DestroyQueue(SqQueue sq)
{

}

//进队
int EnQueue(SqQueue & sq, ElemType x)
{
	if ((sq.rear + 1) % MaxSize == sq.front)
		return 0;
	sq.rear = (sq.rear + 1) % MaxSize;
	sq.data[sq.rear] = x;
	return 1;
}


//出队
int DeQueue(SqQueue & sq, ElemType& x)
{
	if (sq.rear == sq.front)
		return 0;
	sq.front = (sq.front + 1) % MaxSize;
	x = sq.data[sq.front];
	return 1;
}


//取队头元素
int GetHead(SqQueue sq, ElemType& x)
{
	if (sq.rear == sq.front)
		return 0;
	x = sq.data[(sq.front + 1) % MaxSize];
	return 1;
}

//判断队空运算  
int QueueEmpty(SqQueue sq)
{
	if (sq.rear == sq.front)//队空返回1
		return 1;
	else
		return 0;
}

//报数
void Count(int n)
{
	int i;
	int count = 1;			//count用来记第几个元素
	SqQueue sq;
	InitQueue(sq);
	for( i = 1; i <= n; i++ )
	{
		EnQueue(sq,i);
	}
	while (!QueueEmpty(sq))
	{
		DeQueue(sq, i);
		if (count % 2 == 0)
		{
			EnQueue(sq, i);			//第偶数个元素时,进队
		}
		else
		{
		
			printf("%d  ", i);		//第奇数个元素时,出队输出
		}
		count++;
	}
	printf("\n");
	DestroyQueue(sq);
}

源文件

#include"SqQueue.h"
int main()
{
	int num;
	printf("输入个数:");
	scanf("%d", &num);
	Count(num);
	return 0;
}

点个赞再走!!!

 

你可能感兴趣的:(数据结构,c语言,开发语言,后端)