3.随机产生10个100以内的整数建立循环队列,显示循环队列中所有数据元素;从键盘输入出队元素个数 n (1<= n <=10),将 n 个元素出队后显示队中剩余元素;
4.随机产生10个100以内的整数建立循环队列,显示循环队列中所有数据元素;从键盘输入出队元素个数 n (1<= n <=10),将 n 个元素出队后显示此时的队头元素;
cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int QueueSize = 100;
template<typename DataType>
class CirQueue {
public:
CirQueue();
void EnQueue(DataType x);
DataType DeQueue();
DataType GetQueue();
bool Empty();
void Display();
DataType data[QueueSize];
int front, rear;
};
template <typename DataType>
CirQueue<DataType>::CirQueue() {
front = rear = -1;
}
template <typename DataType>
void CirQueue<DataType>::EnQueue(DataType x) {
if ((rear + 1) % QueueSize == front) {
throw "上溢";
}
if (rear == -1) {
front = 0;
}
rear = (rear + 1) % QueueSize;
data[rear] = x;
}
template <typename DataType>
DataType CirQueue<DataType>::DeQueue() {
if (Empty()) {
throw"下溢";
}
DataType x = data[front];
if (front == rear && front == -1) {
front = rear = -1;
}
else {
front = (front + 1) % QueueSize;
}
return x;
}
template <typename DataType>
DataType CirQueue<DataType>::GetQueue() {
if (Empty()) {
throw "队列为空";
}
return data[front];
}
template <typename DataType>
bool CirQueue<DataType>::Empty() {
return front == -1;
}
template <typename DataType>
void CirQueue<DataType>::Display() {
if (Empty()) {
cout << "队列为空" << endl;
return;
}
cout << "队列中的元素为:";
int current = front;
do {
cout << data[current] << " ";
current = (current + 1) % QueueSize;
} while (current != rear);
cout << endl;
}
int main()
{
srand(time(nullptr));
CirQueue<int> queue;
cout << "建立循环队列并显示所有元素:" << endl;
for (int i = 0; i < 10; ++i) {
int num = rand() % 100 + 1;
queue.EnQueue(num);
cout << num << " ";
}
cout << endl;
queue.Display();
int n;
cout << "请输入出队元素个数 n (1<= n <=10):";
cin >> n;
cout << "出队 " << n << " 个元素后,队列中剩余元素为:" << endl;
for (int i = 0; i < n; ++i) {
queue.DeQueue();
}
queue.Display();
cout << "此时的对头元素为" << endl;
cout<< queue.GetQueue();
return 0;
}