You need to enable JavaScript to run this app. C++单链表如何实现删除指定节点后同步移除相邻后续节点
优惠活动
大模型
产品
解决方案
定价
更多

C++单链表如何实现删除指定节点后同步移除相邻后续节点

调整逻辑说明

核心实现规则:每匹配到key值为k的目标节点时,摘除该节点的同时,直接连带摘除它在原链表中紧邻的下一个相邻节点,完全匹配你给出的示例效果:原链路(1,2)->(2,3)->(3,4)->(4,5)调用deleteNodeByKey(1)后,直接跳过两个连续节点,将头指针指向(3,4)节点,最终剩余链路(3,4)->(4,5)。
调整过程中同时修复了原代码的几个冗余/隐患问题:

  • 去掉了重复的空链表判断分支,补上了空判断后的return,避免无意义的流程跳转
  • 修复了原代码找到目标就强制设空循环指针的低效写法,匹配到目标后直接处理并退出遍历
  • 补上了被摘除节点的内存释放逻辑,避免原代码只断链不释放的内存泄漏问题
  • 做了边界适配:如果目标节点已经是链表尾节点,没有可连带删除的相邻节点时,仅删除目标本身,不会出现空指针访问
修改后的完整函数代码
void deleteNodeByKey(int k) {
    if (head == NULL) {
        cout << "Singly Linked List already Empty. Cant delete" << endl;
        return;
    }

    // 场景1:要删除的目标是头节点
    if (head->key == k) {
        node* targetNode = head;
        node* adjacentNextNode = head->next;
        
        // 头指针直接移动到两个被删节点的后方
        if (adjacentNextNode != NULL) {
            head = adjacentNextNode->next;
            cout << "Node UNLINKED with keys value : " << k << endl;
            cout << "Adjacent next Node UNLINKED with keys value : " << adjacentNextNode->key << endl;
            delete adjacentNextNode;
        } else {
            head = NULL;
            cout << "Node UNLINKED with keys value : " << k << endl;
        }
        delete targetNode;
        return;
    }

    // 场景2:要删除的目标在链表非头部位置
    node* prevptr = head;
    node* currentptr = head->next;
    while (currentptr != NULL) {
        if (currentptr->key == k) {
            node* targetNode = currentptr;
            node* adjacentNextNode = currentptr->next;
            // 前驱节点的链直接连接到两个被删节点的后方
            prevptr->next = adjacentNextNode == NULL ? NULL : adjacentNextNode->next;
            
            cout << "Node UNLINKED with keys value : " << k << endl;
            // 相邻节点存在时才执行连带删除
            if (adjacentNextNode != NULL) {
                cout << "Adjacent next Node UNLINKED with keys value : " << adjacentNextNode->key << endl;
                delete adjacentNextNode;
            }
            delete targetNode;
            return;
        }
        prevptr = prevptr->next;
        currentptr = currentptr->next;
    }

    // 全链表遍历完都未找到匹配key的目标节点
    cout << "Node Doesn't exist with key value : " << k << endl;
}
效果验证

以你给出的示例链路测试:

  1. 初始链路:(1,2) -> (2,3) -> (3,4) -> (4,5)
  2. 调用deleteNodeByKey(1)
  3. 程序识别到头节点key=1为目标,连带删除紧随的(2,3)节点,将head直接指向(3,4)节点
  4. 最终剩余链路:(3,4) -> (4,5),完全符合预期

内容的提问来源于stack exchange,提问作者darklord

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.15 06:36:04