本关任务:实现循环队列的基本操作:初始化、入队、出队、遍历等并使用这些操作。队列中元素是大写或小写字母。输入输出输入格式:两行第一行是一个正整数n表示出队和入队的次数第二行是n次出队和入队操作序列其中1表示入队0表示出队如果是入队则1后跟一个大写或小写字母。输出格式:遍历队列内容从队尾到队首输出所有字母如果队为空则输出Queue Empty!输入输出样例:输入51f1e1d00输出:e给我c++代
#include
const int MAX_SIZE = 100; // 队列的最大容量
class CircularQueue { private: char data[MAX_SIZE]; // 存储队列元素的数组 int front; // 队头指针 int rear; // 队尾指针 public: // 初始化队列 CircularQueue() { front = rear = 0; }
// 判断队列是否为空
bool isEmpty() {
return front == rear;
}
// 判断队列是否已满
bool isFull() {
return (rear + 1) % MAX_SIZE == front;
}
// 入队
void enqueue(char value) {
if (isFull()) {
cout << "Queue Full!" << endl;
return;
}
rear = (rear + 1) % MAX_SIZE;
data[rear] = value;
}
// 出队
char dequeue() {
if (isEmpty()) {
cout << "Queue Empty!" << endl;
return '\0';
}
front = (front + 1) % MAX_SIZE;
return data[front];
}
// 遍历队列
void traverse() {
if (isEmpty()) {
cout << "Queue Empty!" << endl;
return;
}
int index = rear;
while (index != front) {
cout << data[index] << endl;
index = (index - 1 + MAX_SIZE) % MAX_SIZE;
}
}
};
int main() { int n; cin >> n; CircularQueue queue; for (int i = 0; i < n; i++) { int operation; char value; cin >> operation; if (operation == 1) { cin >> value; queue.enqueue(value); } else if (operation == 0) { queue.dequeue(); } } queue.traverse(); return 0;
原文地址: https://www.cveoy.top/t/topic/h2Id 著作权归作者所有。请勿转载和采集!