以下是一个入侵链表的简单实现示例,以及如何使用它:
#include <iostream>
// 定义一个简单的链表节点
struct Node {
int data;
Node* next;
};
// 入侵链表的节点,将链表指针放在节点内部
struct IntrusiveNode {
int data;
IntrusiveNode* next;
// 构造函数
IntrusiveNode(int d) : data(d), next(nullptr) {}
// 在节点内部定义插入函数
void insertAfter(IntrusiveNode* newNode) {
newNode->next = next;
next = newNode;
}
// 在节点内部定义删除函数
void removeAfter() {
if (next) {
IntrusiveNode* temp = next;
next = next->next;
delete temp;
}
}
};
// 入侵链表类
class IntrusiveLinkedList {
public:
IntrusiveNode* head;
// 构造函数
IntrusiveLinkedList() : head(nullptr) {}
// 插入节点
void insert(int data) {
IntrusiveNode* newNode = new IntrusiveNode(data);
if (!head) {
head = newNode;
} else {
head->insertAfter(newNode);
}
}
// 删除节点
void remove() {
if (head) {
IntrusiveNode* temp = head;
head = head->next;
delete temp;
}
}
// 打印链表
void print() {
IntrusiveNode* current = head;
while (current) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
};
int main() {
// 创建一个入侵链表对象
IntrusiveLinkedList list;
// 插入一些节点
list.insert(1);
list.insert(2);
list.insert(3);
// 打印链表
list.print();
// 删除一个节点
list.remove();
// 再次打印链表
list.print();
return 0;
}
这只是入侵链表的一个简单实现示例。在实际应用中,入侵链表可以根据具体需求进行更复杂的设计和实现。希望这个示例能够帮助你理解入侵链表的基本概念和用法。