(数据结构)循环队列的入队出队算法

#include
#include
#define MAXSIZE 1024
typedef struct SequenQueue
{
	int data[MAXSIZE];  //定义顺序队列为一维数组
	int front;   //头指针
	int rear;    //尾指针
}SequenQuene;
//循环队列的初始化
SequenQuene* Init_sequenQuene()
{
	SequenQuene* Q;
	Q = (SequenQuene*)malloc(sizeof(SequenQuene));
	if (Q == NULL)
	{
		printf("申请循环队列空间失败,程序结束\n");
		return NULL;
	}
	else
	{
		Q->front = 0;
		Q->rear = 0;
	}
	return Q;
}
//判断队列为空
int SequenQuene_Empty(SequenQuene* Q)
{
	if (Q->front == Q->rear)
	{
		printf("栈为空\n");
		return 1;  //栈空
	}
	else
	{
		return 0;  //栈不为空
	}
}
//判断队列为满
int SequenQuene_Full(SequenQuene* Q)
{
	if ((Q->rear + 1) % MAXSIZE == Q->front)  //栈的尾指针的下一位取余如果等于头指针,则判断栈满
	{
		return 1;  //栈满
	}
	else
	{
		return 0;  //栈不为满
	}
}
//求循环队列的长度
int SequenQuene_Length(SequenQuene* Q)
{
	return (Q->rear - Q->front + MAXSIZE) % MAXSIZE;   //尾指针-头指针得到它们的较短相隔的空白内存距离(负数),
	//加上整个队列的内存大小再取余后,得到的是有数据的内存空间距离
}
//入队
int Enter_SequenQuene(SequenQuene* Q, int x)
{
	if (SequenQuene_Full(Q))
	{
		return 0;
	}
	Q->data[Q->rear] = x;   //尾指针处赋值
	Q->rear = (Q->rear + 1) % MAXSIZE;  //尾指针向前一位
	return 1;
}
//出队
int Delete_SequenQuene(SequenQuene* Q, int* x)
{
	if (SequenQuene_Empty(Q)) //判断队列是否为空
	{
		return 0;
	}
	else
	{
		*x = Q->data[Q->front];  //将对头元素赋值给x
		Q->front = (Q->front + 1) % MAXSIZE;   //将队头向后移一位
	}
	return 1;
}
//取队头数据元素
int GetFront_SequenQuene(SequenQuene* Q, int* x)
{
	if (SequenQuene_Empty(Q)) //判断队列是否为空
	{
		return 0;
	}
	else
	{
		*x = Q->data[Q->front];  //将对头元素赋值给x
		return 1;
	}
}
int main()
{
	SequenQuene* Q;
	Q = Init_sequenQuene();
	while (1)
	{
		printf("输入1为入队,输入0为退队\n");
		int ret;
		printf("请输入选项\n");
		scanf("%d", &ret);
		if (ret == 1)
		{
			int x;
			printf("请输入需要入队的值\n");
			scanf("%d", &x);
			Enter_SequenQuene(Q, x);
			continue;
		}
		else if (ret == 0)
		{
			int y = 0;
			Delete_SequenQuene(Q, &y);
			printf("出队的值为:\n");
			printf("%d \n", y);
			continue;
		}
		else
		{
			printf("选项输入错误\n");
		}
	}
	return 0;
}

你可能感兴趣的:(数据结构,数据结构,算法)