入侵链表(Intrusive Linked List)

以下是一个入侵链表的简单实现示例,以及如何使用它:

#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;
}

这只是入侵链表的一个简单实现示例。在实际应用中,入侵链表可以根据具体需求进行更复杂的设计和实现。希望这个示例能够帮助你理解入侵链表的基本概念和用法。

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值