数据结构:C++实现循环队列

#include<iostream>
using namespace std;
#define MAXSIZE 10//定义数组长度
//定义队列结构体,结构体中包含int类型数组的首地址base和队列的头指针和尾指针
struct queue
{
	int* base;
	int front;
	int rear;
};
//初始化队列
void initqueue(queue &q)
{
	q.base = new int[MAXSIZE];
	if (!q.base)
	{
		return;
	}
	q.front = 0;
	q.rear = 0;
}
//获取队列的长度
//由于采用循环队列,计算公式如下,可以自行画图查看
int queuelength(queue q)
{
	return (q.rear - q.front + MAXSIZE) % MAXSIZE;
}
//从队尾插入数据
void enqueue(queue &q, int e)
{
	if ((q.rear + 1) % MAXSIZE == q.front)
	{
		cout << "队列已满!" << endl;
		return;
	}
	q.base[q.rear] = e;
	cout << q.base[q.rear] << endl;
	q.rear = (q.rear + 1) % MAXSIZE;
	cout << "rear:" << q.rear << endl;
}
//从队头弹出数据
void popque(queue &q, int &e)
{
	if (q.front == q.rear)
	{
		cout << "队列为空!" << endl;
		return;
	}
	e = q.base[q.front];
	q.front = (q.front + 1) % MAXSIZE;
}
//获取头节点数据
int gethead(queue q)
{
	if (q.front == q.rear)
	{
		cout << "队列为空!" << endl;
	}
	else
	{
		return q.base[q.front];
	}
}
int main()
{
	queue q;
	initqueue(q);
	int a = 0, b = 1, c = 2;
	enqueue(q, a);
	enqueue(q, b);
	enqueue(q, c);
	for (int i = 0; i < 3; i++)
	{
		cout << q.base[i] << endl;
	}
	cout << queuelength(q) << endl;
	system("pause");
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值