循环队列的实现,插入,删除,打印,求长度

#include<iostream>
#define MAXSIZE 10
#define OK 1
#define ERROR 0
using namespace std;
typedef int	QElemType;

//定义循环队列结构
typedef struct 
{
	QElemType *base;	//初始化的动态分配存储空间
	int front;		//头指针,若队列不为空,指向队头元素
	int rear;		//尾指针,若队列不为空,指向队尾元素的下一个位置
				//注:front,rear本身不是指针,是两个下标,类似数组的下标
}SqQueue;

//创建循环队列
int InitQueue(SqQueue &Q)
{
	Q.base = (QElemType *)malloc(MAXSIZE *sizeof(QElemType));
	if (!Q.base) return ERROR;
	Q.front = Q.rear = 0;	//初始时,头尾指针均为0;
	return OK;
}

//返回循环队列数据长度
int QueueLength(SqQueue Q)
{
	return (Q.rear - Q.front + MAXSIZE) % MAXSIZE;
}

//队头插入元素
void EnQueue(SqQueue &Q, QElemType e)
{
	if ((Q.rear + 1) % MAXSIZE == Q.front) cout << "队列已满!" << endl;
	Q.base[Q.rear] = e;
	Q.rear = (Q.rear + 1) % MAXSIZE;	//%的作用:当Q.rear+1达到MAXSIZE时,Q.rear从0开始
}

//删除队尾元素
void DeQueue(SqQueue &Q)
{
	if (Q.rear == Q.front) cout << "循环队列为空,删除失败!" << endl;
	Q.front = (Q.front + 1) % MAXSIZE;	
	cout <<"循环队列队头元素"<<Q.base[Q.front-1]<<"删除成功!" << endl;
}

//打印循环队列
void PrintQueue(SqQueue &Q)
{
	int i,length;
	length = QueueLength(Q);
	cout << "循环队列元素:" << endl;
	for (i = 0; i < length; i++)
	{
		cout << Q.base[(Q.front + i) % MAXSIZE] << endl;
	}
}
void main()
{
	SqQueue Q;
	QElemType length;
	int i = 0;
	cout << endl << endl << "循环队列的实现";
	cout << endl << "==============";
	if (InitQueue(Q))
		cout << endl << endl << "Success ! The SqQueue has been initilized !" << endl;
	EnQueue(Q, 1);
	EnQueue(Q, 2);
	EnQueue(Q, 3);
	EnQueue(Q, 4);
	EnQueue(Q, 5);
	EnQueue(Q, 6);
	PrintQueue(Q);

	DeQueue(Q);
	PrintQueue(Q);
	system("pause");
}


  • 10
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

sky@sea

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

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

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

打赏作者

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

抵扣说明:

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

余额充值