循环队列的使用·数据结构

在讲循环队列之前,先来聊聊队列吧
队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。

而循环队列是什么呢?由于队列存在着假溢出(即队列未满,但是尾指针到了末尾的位置,使队列无法再进行入队的操作)。为了解决假溢出,程序员发明了循环队列,使头尾指针的使用更加的灵活,可以有效地解决假溢出的问题。

在循环队列中,实现的最关键的步骤是模运算

我们先来看看头文件的代码吧

头文件: 

#pragma once
#include<iostream>
using namespace std;
#define MAXSIZE 100
//循环队列类
class CyclicQ {
private:
	int* data;//数组
	int front;//队头指针
	int rear;//队尾指针
public:
	//初始化
	void Init() {
		data = new int[MAXSIZE];
		front = rear = 0;
	}
	//求当前队列长度
	int Getlen() {
		return (rear - front + MAXSIZE) % MAXSIZE;
	}
	//输出
	void Output() {
		int len = Getlen();
		cout << "队列长度:" << len << endl;
		if (len > 0) {
			cout << "队列内容:" << endl;
			int index = (front + 1) % MAXSIZE;//指向第一个元素
			for (int i = 0; i < len; i++) {
				cout << data[index] << "|";
				index = (index + 1) % MAXSIZE;
			}
			cout << endl;
		}
	}
	//入队
	void EnQueue(int value) {
		rear = (rear + 1) % MAXSIZE;
		data[rear] = value;
	}
	//出队
	int DeQueue() {
		front = (front + 1) % MAXSIZE;
		return data[front];
	}
	//判空
	bool isEmpty() {
		return(front == rear) ? true : false;
	}
	//判满
	bool isFull() {
		return (front == ((rear + 1) % MAXSIZE)) ? true : false;
	}
	//销毁
	void Destroy() {
		delete[]data;
	}
	//取队头元素
	int GetTop() {
		int temp = (front + 1) % MAXSIZE;
		return data[temp];
	}
};

头文件包含了一个数组,头尾指针以及一系列的函数,读者们仔细阅读可以清楚的理解它们
再看看main函数

main函数:

#include<iostream>
#include"严严的循环队列.h"
using namespace std;
int main()
{
	CyclicQ c;
	c.Init();
	c.Output();
	cout << "队空?" << c.isEmpty() << endl;
	cout << "队满?" << c.isFull() << endl;
	for (int i = 1; i <= 99; i++) {
		c.EnQueue(i);
	}
	c.Output();
	for (int i = 1; i <= 50; i++) {
		int t = c.DeQueue();
		cout << "出队元素:" << t << endl;
	}
	c.Output();
	cout << c.GetTop() << endl;
	cout << "队空?" << c.isEmpty() << endl;
	cout << "队满?" << c.isFull() << endl;
	system("pause");
	return 0;
}

 

 PS:简单易懂
明天将更新杨辉三角(用队列的方式实现)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

白凤倚剑归

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

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

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

打赏作者

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

抵扣说明:

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

余额充值