用C++ 编写一个程序实现链队列的各种基本运算,并在此基础上设计一个主程序,完成如下功能: 初始化链队列;入队;出队;判断队列是否为空
时间: 2023-06-24 16:06:26 浏览: 155
数据结构与算法C++实现 循环顺序队列的初始化,求长度,入队,出队
5星 · 资源好评率100%
以下是C++代码实现链队列的各种基本运算:
```cpp
#include <iostream>
using namespace std;
// 定义链队列的结构体
struct QueueNode {
int data;
QueueNode* next;
};
class LinkedQueue {
private:
QueueNode* front; // 队首指针
QueueNode* rear; // 队尾指针
public:
LinkedQueue() {
front = rear = new QueueNode;
front->next = NULL;
}
~LinkedQueue() {
Clear();
delete front;
}
void EnQueue(int x) { // 入队操作
QueueNode* p = new QueueNode;
p->data = x;
p->next = NULL;
rear->next = p;
rear = p;
}
int DeQueue() { // 出队操作
if (front == rear) {
cout << "队列为空,无法出队!" << endl;
return -1;
}
QueueNode* p = front->next;
int x = p->data;
front->next = p->next;
if (rear == p) {
rear = front;
}
delete p;
return x;
}
void Clear() { // 清空队列
while (front->next != NULL) {
QueueNode* p = front->next;
front->next = p->next;
delete p;
}
rear = front;
}
bool IsEmpty() { // 判断队列是否为空
return front == rear;
}
};
```
以下是主程序,完成初始化链队列、入队、出队和判断队列是否为空的功能:
```cpp
int main() {
LinkedQueue queue;
int choice, x;
while (true) {
cout << "请选择操作:" << endl;
cout << "1. 入队" << endl;
cout << "2. 出队" << endl;
cout << "3. 判断队列是否为空" << endl;
cout << "4. 清空队列" << endl;
cout << "5. 退出程序" << endl;
cin >> choice;
switch (choice) {
case 1:
cout << "请输入要入队的元素:";
cin >> x;
queue.EnQueue(x);
break;
case 2:
x = queue.DeQueue();
if (x != -1) {
cout << "出队元素为:" << x << endl;
}
break;
case 3:
if (queue.IsEmpty()) {
cout << "队列为空!" << endl;
} else {
cout << "队列不为空!" << endl;
}
break;
case 4:
queue.Clear();
cout << "队列已清空!" << endl;
break;
case 5:
return 0;
default:
cout << "输入的操作不合法,请重新输入!" << endl;
break;
}
}
}
```
这样,我们就实现了链队列的各种基本运算,并且设计了一个主程序,完成了初始化链队列、入队、出队和判断队列是否为空的功能。
阅读全文