在讲循环队列之前,先来聊聊队列吧
队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(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:简单易懂
明天将更新杨辉三角(用队列的方式实现)