队空条件:front == rear
队满条件:(rear + 1) % mSize == front
队列长度:(rear - front + mSize) % QueueSize
#include<iostream>
#define MAXSIZE 10
using namespace std;
class CirQueue {
private:
int *data; //指向队列存储空间
int front = 0; //队首下标
int rear = 0; //队尾下标
int mSize; //存放队列的数组大小
public:
CirQueue(int size); //建立长度为size的队列
~CirQueue(); //清空队列,释放内存
void pushQueue(int item); //入队
void popQueue(); //出队
void getFront(); //读取队首元素,但不删除;
bool isEmpty(); //判断队列是否为空
bool isFull(); //判断队列是否为满
void clearQueue(); //清空队列
void displayQueue(); //显示队列内容
void queueLength(); //获取队列元素个数;
};
CirQueue::CirQueue(int size)
{
data = new int[size];
front = 0;
rear = 0;
mSize = size + 1;
}
CirQueue::~CirQueue()
{
if (data != nullptr)
delete[]data;
rear = front = 0;
}
void CirQueue::pushQueue(int n)
{
cout << "请输入需要添加的数字:" << endl;
for (int i = 0; i < n; i++)
{
if (isFull())
{
cout << "队列已满" << endl;
return;
}
cin >> data[rear];
rear = (rear + 1) % mSize;
}
}
void CirQueue::popQueue()
{
int n;
cout << "请输入需要删除的元素个数:" << endl;
cin >> n;
for (int i = 0; i < n; i++)
{
if (isEmpty())
{
cout << "队列已空" << endl;
return;
}
cout << data[front] << " ";
front = (front + 1) % mSize;
}
cout << endl;
}
void CirQueue::getFront()
{
if (isEmpty())
{
cout << "队列为空" << endl;
return;
}
cout << data[front] << endl;
}
bool CirQueue::isEmpty()
{
return rear == front;
}
bool CirQueue::isFull()
{
return (rear + 1) % mSize == front;
}
void CirQueue::displayQueue()
{
for (int i = front; i != rear;)
{
cout << data[i] << " ";
i = (i + 1) % mSize;
}
cout << endl;
}
void CirQueue::clearQueue()
{
front = rear = 0;
return;
}
void menu()
{
cout << "-------------------1.退出 2.清空队列---------------------" << endl;
cout << "-------------------3.入队 4.出队-------------------------" << endl;
cout << "-------------------5.遍历队列 6.队首元素---------------------" << endl;
cout << "-------------------7.销毁队列 8.队列长度---------------------" << endl;
}
void CirQueue::queueLength()
{
cout << "队列长度为: " << (rear - front + mSize) % mSize << endl;
return;
}
int main()
{
int choice, n, size;
cout << "请输入队列长度" << endl;
cin >> size;
CirQueue cq(size);
while (1)
{
menu();
cin >> choice;
if (choice == 1)
break;
switch (choice)
{
case 2:
cq.clearQueue();break;
case 3:
cout << "请输入需要添加的数字个数:" << endl;
cin >> n;
cq.pushQueue(n);
break;
case 4:
cq.popQueue(); break;
case 5:
cq.displayQueue(); break;
case 6:
cq.getFront(); break;
case 7:
cq.~CirQueue(); break;
case 8:
cq.queueLength(); break;
default:
break;
}
}
return 0;
}