双向链表(Doubly Linked List)是一种链式数据结构,其中每个节点包含三个部分:数据域、前驱指针(指向前一个节点)和后继指针(指向后一个节点)。这种结构允许从任意节点向前或向后遍历链表。
双向链表广泛应用于需要频繁插入和删除操作的场景,例如:
以下是一个C++实现双向链表插入方法的示例代码:
#include <iostream>
// 定义双向链表节点结构
struct Node {
int data;
Node* prev;
Node* next;
Node(int val) : data(val), prev(nullptr), next(nullptr) {}
};
// 定义双向链表类
class DoublyLinkedList {
public:
DoublyLinkedList() : head(nullptr), tail(nullptr) {}
// 头插法
void insertAtHead(int value) {
Node* newNode = new Node(value);
if (!head) {
head = tail = newNode;
} else {
newNode->next = head;
head->prev = newNode;
head = newNode;
}
}
// 尾插法
void insertAtTail(int value) {
Node* newNode = new Node(value);
if (!tail) {
head = tail = newNode;
} else {
newNode->prev = tail;
tail->next = newNode;
tail = newNode;
}
}
// 中间插法
void insertAtPosition(int value, int position) {
if (position <= 0) {
insertAtHead(value);
return;
}
Node* newNode = new Node(value);
Node* current = head;
int count = 0;
while (current && count < position - 1) {
current = current->next;
count++;
}
if (!current) {
insertAtTail(value);
} else {
newNode->next = current->next;
newNode->prev = current;
if (current->next) {
current->next->prev = newNode;
} else {
tail = newNode;
}
current->next = newNode;
}
}
// 打印链表
void printList() {
Node* current = head;
while (current) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
private:
Node* head;
Node* tail;
};
int main() {
DoublyLinkedList list;
list.insertAtHead(1);
list.insertAtTail(3);
list.insertAtPosition(2, 2);
list.printList(); // 输出: 1 2 3
return 0;
}
通过以上内容,你应该对双向链表的插入方法有了全面的了解,包括基础概念、优势、类型、应用场景以及常见问题的解决方法。
领取专属 10元无门槛券
手把手带您无忧上云