链式队列的基本操作c++
时间: 2023-12-06 21:36:06 浏览: 93
链式队列是一种基于链表实现的队列,它的基本操作包括入队和出队。以下是链式队列的基本操作C++代码:
```C++
#include <iostream>
using namespace std;
// 链式队列结点的定义
template <typename T>
struct Node {
T data;
Node<T>* next;
};
// 链式队列的定义
template <typename T>
class LQueue {
public:
LQueue() {
front = rear = new Node<T>;
front->next = NULL;
}
~LQueue() {
while (front) {
rear = front->next;
delete front;
front = rear;
}
}
bool IsEmpty() const {
return front == rear;
}
void EnQueue(const T& x) {
rear->next = new Node<T>;
rear = rear->next;
rear->data = x;
rear->next = NULL;
}
bool DeQueue(T& x) {
if (IsEmpty()) {
return false;
}
Node<T>* p = front->next;
x = p->data;
front->next = p->next;
if (rear == p) {
rear = front;
}
delete p;
return true;
}
private:
Node<T>* front;
Node<T>* rear;
};
// 测试代码
int main() {
LQueue<int> q;
for (int i = 1; i <= 5; ++i) {
q.EnQueue(i);
}
int x;
while (!q.IsEmpty()) {
q.DeQueue(x);
cout << x << " ";
}
cout << endl;
return 0;
}
```
阅读全文