用c++,编写程序s,实现链式队列的各种运算,并在此基础上设计主程序main
时间: 2023-10-10 08:15:42 浏览: 128
以下是链式队列的实现,包括入队、出队、判空等操作:
```c++
#include <iostream>
using namespace std;
// 链式队列结点定义
template<typename T>
struct QueueNode {
T data;
QueueNode<T>* next;
};
// 链式队列定义
template<typename T>
class LinkedQueue {
public:
LinkedQueue() {
front_ = rear_ = new QueueNode<T>; // 初始化头结点
front_->next = nullptr;
}
~LinkedQueue() {
ClearQueue();
delete front_; // 释放头结点
front_ = rear_ = nullptr;
}
bool EnQueue(const T& e) {
QueueNode<T>* node = new QueueNode<T>;
node->data = e;
node->next = nullptr;
rear_->next = node;
rear_ = node;
return true;
}
bool DeQueue(T& e) {
if (IsEmpty()) {
return false;
}
QueueNode<T>* node = front_->next;
e = node->data;
front_->next = node->next;
if (rear_ == node) {
rear_ = front_;
}
delete node;
return true;
}
bool IsEmpty() const {
return front_ == rear_;
}
void ClearQueue() {
while (!IsEmpty()) {
T e;
DeQueue(e);
}
}
private:
QueueNode<T>* front_; // 队头指针
QueueNode<T>* rear_; // 队尾指针
};
// 主函数
int main() {
LinkedQueue<int> q;
int choice, x;
do {
cout << "1. EnQueue" << endl;
cout << "2. DeQueue" << endl;
cout << "3. ClearQueue" << endl;
cout << "4. Exit" << endl;
cout << "Please input your choice:" << endl;
cin >> choice;
switch (choice) {
case 1:
cout << "Please input the element you want to enqueue:" << endl;
cin >> x;
q.EnQueue(x);
break;
case 2:
if (q.DeQueue(x)) {
cout << "The element dequeued is " << x << endl;
} else {
cout << "The queue is empty." << endl;
}
break;
case 3:
q.ClearQueue();
cout << "The queue has been cleared." << endl;
break;
case 4:
break;
default:
cout << "Invalid choice." << endl;
break;
}
} while (choice != 4);
return 0;
}
```
在主函数中,我们提供了四个操作:入队、出队、清空队列和退出程序。用户可以根据提示输入相应的操作编号和元素值。当用户选择出队操作时,程序会输出出队的元素值,如果队列为空则输出提示信息。
阅读全文