用C语言实现队列的顺序结构

用C语言实现队列的初始化、队列的判空操作、入队操作、出队运算、取队头元素运算、顺序打印队列。

#include<stdio.h>
#define QueueSize 100
typedef char ElemType;
typedef struct//队列结构体
{
	ElemType data[QueueSize];//保存队中元素
	int front, rear;//队头和队尾指针
} SqQueue;
//队列的初始化
void InitQueue(SqQueue*qu)
{
	qu->rear = qu->front;//指针初始化
}
//队列的判空操作
int QueueEmpty(SqQueue*qu)//判断队空运算
{
	if (qu->front ==qu->rear)//队空
	{
		return 1;
	}
	else
	{
		return 0;
	}
}
//入队操作
int EnQueue(SqQueue*qu, ElemType x)
{
	if ((qu->rear + 1) % QueueSize == qu->front) //表示队列已经满了
	{
		return 0;
	}
	qu->rear = (qu->rear + 1) % QueueSize; //队尾指针进1
	qu->data[qu->rear] = x;
	return 1;
}
//出队运算
int DeQueue(SqQueue*qu, ElemType*x)
{
	if (QueueEmpty(qu))
	{
		return 0;
	}
	*x = qu->data[qu->front];
	qu->front = (qu->front + 1) % QueueSize;//队头指针进1
	return 1;
}
//取队头元素运算
int GetHead(SqQueue*qu, ElemType*x)
{
	if (qu->rear == qu->front)//队空
	{
		return 0;
	}
	*x = qu->data[(qu->front + 1) % QueueSize];
	{
		return 1;
	}
}
//顺序打印队列
void printQueue(SqQueue* qu)
{
	for (int i = qu->front; i != qu->rear; i = (i + 1) % QueueSize)
	{
		printf("%c", qu->data[i+1]);
	}
	printf("\n");
}
void main()
{
	SqQueue qu;
	ElemType e;
	InitQueue(&qu);
	printf("队%s\n", (QueueEmpty(&qu) == 1 ? "空" : "不空"));
	printf("a进队\n");
	EnQueue(&qu,'a');
	printf("b进队\n");
	EnQueue(&qu,'b');
	printf("c进队\n");
	EnQueue(&qu,'c');
	printf("d进队\n");
	EnQueue(&qu,'d');
	printf("打印队列中的元素:");
	printQueue(&qu);
	printf("队%s\n", (QueueEmpty(&qu) == 1 ? "空" : "不空"));
	GetHead(&qu,&e);
	printf("队头元素:%c\n",e);
	printf("出队次序:");
	printQueue(&qu);
	printf("\n");
}

运行结果: 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清潇沈默

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值