用C++写一段代码定义一个双向链表类以及其常用功能
时间: 2024-09-23 12:15:50 浏览: 46
在C++中,我们可以定义一个双向链表类(Doubly Linked List),包含节点结构体、头指针和一些基本操作函数,如插入、删除、遍历等。以下是简单的代码示例:
```cpp
#include <iostream>
// 定义链表节点结构
struct Node {
int data;
Node* prev;
Node* next;
};
class DoublyLinkedList {
public:
// 构造函数,初始化空链表
DoublyLinkedList() : head(nullptr), tail(nullptr) {}
// 插入节点到链表头部
void insertAtStart(int value) {
Node* newNode = new Node{value, nullptr, head};
if (head) head->prev = newNode;
head = newNode;
if (!tail) tail = newNode;
}
// 插入节点到链表尾部
void insertAtEnd(int value) {
Node* newNode = new Node{value, tail, nullptr};
if (tail) tail->next = newNode;
tail = newNode;
if (!head) head = newNode;
}
// 删除指定值的节点
void removeNode(int value) {
Node* curr = head;
while (curr) {
if (curr->data == value) {
if (curr->prev) curr->prev->next = curr->next;
else head = curr->next;
if (curr->next) curr->next->prev = curr->prev;
else tail = curr->prev;
delete curr;
return;
}
curr = curr->next;
}
}
// 遍历链表并打印元素
void display() {
Node* temp = head;
while (temp) {
std::cout << temp->data << " ";
temp = temp->next;
}
std::cout << "\n";
}
private:
Node* head; // 链表头节点
Node* tail; // 链表尾节点
};
int main() {
DoublyLinkedList list;
list.insertAtStart(5);
list.insertAtStart(3);
list.insertAtEnd(7);
list.display();
list.removeNode(5);
list.display();
return 0;
}
```
阅读全文