C++:编程实现对循环链队列的入队和出队操作。 (1)实验要求 ① 根据输入的队列长度n和各元素值建立一个带头结点的循环链表表示的队列(循环链队列),并且只设一个尾指针来指向尾结点,然后输出队列中各元素值。 ② 将数据元素e入队,并输出入队后的队列中各元素值。 ③ 将循环链队列的队首元素出队,并输出出队元素的值和出队后队列中各元素值。
时间: 2024-02-09 15:09:17 浏览: 77
好的,下面是C++的代码实现:
```c++
#include <iostream>
using namespace std;
// 循环链队列结点结构体
struct QueueNode {
int data; // 数据域
QueueNode* next; // 指向下一个结点的指针
};
// 循环链队列类
class CircularQueue {
public:
CircularQueue(); // 构造函数,初始化循环链队列
~CircularQueue(); // 析构函数,删除循环链队列
void EnQueue(int e); // 入队操作
void DeQueue(); // 出队操作
void Print(); // 输出队列元素
private:
QueueNode* rear; // 尾指针
};
// 构造函数,初始化循环链队列
CircularQueue::CircularQueue() {
rear = new QueueNode;
rear->next = rear;
}
// 析构函数,删除循环链队列
CircularQueue::~CircularQueue() {
QueueNode* p = rear->next;
while (p != rear) {
QueueNode* q = p->next;
delete p;
p = q;
}
delete rear;
}
// 入队操作
void CircularQueue::EnQueue(int e) {
QueueNode* p = new QueueNode;
p->data = e;
p->next = rear->next;
rear->next = p;
rear = p;
Print();
}
// 出队操作
void CircularQueue::DeQueue() {
if (rear->next == rear) { // 队列为空
cout << "队列为空!" << endl;
return;
}
QueueNode* p = rear->next->next;
int e = rear->next->data;
delete rear->next;
rear->next = p;
cout << "出队元素为:" << e << endl;
Print();
}
// 输出队列元素
void CircularQueue::Print() {
cout << "队列元素为:";
if (rear->next == rear) { // 队列为空
cout << "空";
} else {
QueueNode* p = rear->next;
while (p != rear) {
cout << p->data << " ";
p = p->next;
}
cout << p->data;
}
cout << endl;
}
int main() {
int n; // 队列长度
cout << "请输入队列长度n:";
cin >> n;
CircularQueue queue;
cout << "请输入" << n << "个队列元素值:" << endl;
for (int i = 0; i < n; i++) {
int e;
cin >> e;
queue.EnQueue(e);
}
int m; // 入队元素
cout << "请输入要入队的元素值m:";
cin >> m;
queue.EnQueue(m);
queue.DeQueue();
return 0;
}
```
以上代码实现了循环链队列的入队和出队操作,并且根据输入的队列长度和各元素值建立了一个带头结点的循环链表表示的队列。
阅读全文
相关推荐


















