C++用类实现带头指针和尾指针的队列模板
时间: 2023-11-02 08:11:08 浏览: 54
好的,这是一个简单的带头指针和尾指针的队列模板的实现:
```c++
template<typename T>
class Queue {
private:
struct Node {
T data;
Node *next;
Node(T d, Node *n) : data(d), next(n) {}
};
Node *head, *tail;
public:
Queue() : head(nullptr), tail(nullptr) {}
~Queue() {
while(head != nullptr) {
Node *temp = head;
head = head->next;
delete temp;
}
}
void push(const T &data) {
if(head == nullptr) {
head = new Node(data, nullptr);
tail = head;
} else {
tail->next = new Node(data, nullptr);
tail = tail->next;
}
}
void pop() {
if(head != nullptr) {
Node *temp = head;
head = head->next;
delete temp;
}
}
T front() const {
if(head != nullptr) {
return head->data;
}
return T();
}
T back() const {
if(tail != nullptr) {
return tail->data;
}
return T();
}
bool empty() const {
return head == nullptr;
}
};
```
在这个模板中,我们使用了一个内部结构体`Node`来表示队列中的节点,每个节点包含了一条数据`data`和一个指向下一个节点的指针`next`。队列的头和尾分别是指向`Node`类型的指针`head`和`tail`。队列的构造函数初始化了头和尾指针为`nullptr`。队列的`push()`函数在队列尾部添加一个新节点,`pop()`函数删除队列的头节点,`front()`和`back()`分别返回队列的头部和尾部的数据,`empty()`函数判断队列是否为空。在队列的析构函数中,我们使用循环来删除队列中的所有节点。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)