1.顺序实现循环队列
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
const int MAX = 20;
class Myqueue
{
private:
int Queue[MAX] = { 0 };
int front = 0;
int rear = 0;
int size = 0;
public:
void Inque(int n)
{
if (Isfull())
return;
else
{
size++;
Queue[rear] = n;
rear = (rear + 1) % MAX;
}
}
int Deque()
{
if (this->Isempty())
return 0;
else
{
size--;
int temp = Queue[front];
Queue[front] = 0;
front = (front + 1) % MAX;
return temp;
}
}
bool Isempty()
{
if (size == 0)
return true;
else
return false;
}
bool Isfull()
{
if (size == MAX)
return true;
else
return false;
}
int Getsize()
{
return size;
}
void Print()
{
if (Isempty())
{
cout << "队列为空!" << endl;
return;
}
else
{
int temp = front;
cout << "当前队列为:";
if(Isfull())
{
cout << Queue[temp] << ' ';
temp = (temp + 1) % MAX;
}
while (temp != rear)
{
cout << Queue[temp] << ' ';
temp = (temp + 1) % MAX;
}
cout << endl;
}
}
};
int main()
{
Myqueue test;
srand(time(0));
for (int i = 0; i < MAX; i++)
{
test.Inque(rand() % 99+1);
test.Print();
}
int num = 0;
cout << "想要出队几个?:";
cin >> num;
for (int i = 0; i < num; i++)
{
test.Deque();
test.Print();
}
cout << "填满吗?(y/Y):";
char ch;
cin >> ch;
if (ch == 'y' || ch == 'Y')
{
while (!test.Isfull())
{
test.Inque(rand() % 99+1);
test.Print();
}
}
return 0;
}
2.链式实现
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
struct Node
{
int num;
Node* next;
};
class Myqueue
{
private:
Node* head = nullptr;
Node* rear = nullptr;
int size = 0;
public:
~Myqueue()
{
while (!Isempty())
this->Deque();
}
void Inque(int n)
{
Node* temp = new Node;
temp->num = n;
temp->next = nullptr;
if (Isempty())
{
head = temp;
rear = temp;
size++;
}
else
{
rear->next = temp;
rear = temp;
size++;
}
}
void Deque()
{
if (Isempty())
{
cout << "队列已空!" << endl;
return;
}
else if (size == 1)
{
Node* temp = head;
head = nullptr;
rear = nullptr;
delete temp;
size--;
}
else
{
Node* temp = head;
head = head->next;
delete temp;
size--;
}
}
bool Isempty()
{
if (size == 0 && head == nullptr && rear == nullptr)
return true;
else
return false;
}
void Print()
{
if (Isempty())
{
cout << "队列已空!" << endl;
return;
}
else
{
cout << "此队列为:";
Node* temp = head;
do {
cout << temp->num << ' ';
temp = temp->next;
} while (temp != nullptr);
cout << endl;
}
}
};
int main()
{
Myqueue one;
srand(time(0));
int number = rand() % 10 + 1;
cout << "进行" << number << "次循环" << endl;
for (int i = 0; i < number; i++)
{
one.Inque(rand() % 99 + 1);
}
one.Print();
int num = 0;
cout << "出队几次?:";
cin >> num;
for (int i = 0; i < num; i++)
one.Deque();
one.Print();
return 0;
}