1.队列接口
#pragma once
#include<iostream>
const int Max=5;
using namespace std;
class SeqQueue
{
public:
int* QueueArray;
int front, rear;//front为第一个元素的下标,rear为最后一个元素的后一个位置
int maxSize;
int size;
SeqQueue(int max = Max);
bool isEmpty();
void EnQueue(int val);
int DeQueue();
bool overFlow();
void reSize(int newSize);//重新设置长度
void Clear();//清空队列但不删除
void Destory();//删除队列
void display();//输出队列
int getRear();
};
2.基本操作
1.初始化
设rear(指向最后一个元素的后一个位置)和front(指向第一个元素)为0
SeqQueue::SeqQueue(int max)
{
if (max > 0)
{
QueueArray = new int[max];
if (QueueArray == nullptr)
cerr << "存储分配错误" << endl;
for (int i = 0; i < max; i++)
QueueArray[i] = 0;
front = 0;
rear = 0;
size = 0;
this->maxSize = max;
}
else
{
this->maxSize = 0;
front = -1;
rear = -1;
size = 0;
QueueArray = nullptr;
cerr << "无效数组" << endl;
}
}
2.判空
bool SeqQueue::isEmpty()
{
return front==rear;
}
3.入队
1.先判断是否上溢出 2.将元素入队,入队后rear指向最后一个元素的后一个位置
void SeqQueue::EnQueue(int val)
{
if (rear == maxSize)
cout << "上溢出" << endl;
else
{
size++;
QueueArray[rear] = val;
rear++;
}
}
4.出队
1.先判断是否队空
2.将元素出队,出队后front指向第一个元素的后一个位置
int SeqQueue::DeQueue()
{
if (this->front == this->rear)
cout << "空队列" << endl;
else
{
int val = QueueArray[front];
size--;
front++;
return val;
}
}
5.其他操作
重设大小
1.判断新表长是否合理
2.将maxSize设为新表长
3.重新声明一个新数组
4.将旧数组的数组赋值给新数组
5.删除旧数组
6.将新数组设置为Array
void SeqQueue::reSize(int newSize)
{
if (newSize < 0)
{
cerr << "Invalid Data" << endl;
}
if (newSize != maxSize)
{
maxSize = newSize;
int* newArray = new int[maxSize];
if (newArray == nullptr)
{
cerr << "Memory allocate error" << endl;
exit(0);
}
for (int i = 0; i < maxSize; i++)
{
newArray[i] = QueueArray[i];
}
delete[] QueueArray;
QueueArray = newArray;
}
}
清空队列和删除队列
void SeqQueue::Clear()
{
if (QueueArray == nullptr)//若为空表
return;
else
{
for (int i = 0; i <= rear; i++)
QueueArray[i] = 0;
}
}
void SeqQueue::Destory()
{
Clear();
delete[]QueueArray;
}
输出队列
void SeqQueue::display()
{
for (int i = front; i <rear; i++)
{
cout << QueueArray[i] << endl;
}
}
3.测试函数
#include<iostream>
#include<random>
#include"SeqQueue.h"
using namespace std;
int main()
{
SeqQueue Test;
cout << (Test.isEmpty() ? "Test表为空" : "Test表不为空") << endl;
int time;
cout << "输入元素个数为:";
cin >> time;
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> dis(1, 10);
for (int i = 0; i < time; i++)
{
int ele;
ele = dis(gen);
cout << ele << endl;
//cin >> ele;
Test.EnQueue(ele);
}
cout << endl;
Test.display();
cout << endl;
for (int i = 0; i < time; i++)
{
cout<<Test.DeQueue()<<endl;
}
cout << endl;
Test.display();
cout << (Test.isEmpty() ? "Test表为空" : "Test表不为空") << endl;
}