You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++课程项目如何实现允许用户删除自定义链表指定节点功能

链表节点删除功能实现指导

实现逻辑说明

我们以你结构体内的唯一标识字段indcode作为删除匹配规则,你也可以根据需求替换为其他字段或字段组合,核心处理逻辑如下:

  • 链表为空时直接返回删除失败提示
  • 待删除节点是头节点:修改头指针指向原头节点的下一个节点,释放原头节点内存即可
  • 待删除节点是中间/尾部节点:遍历链表找到待删除节点的前驱节点,修改前驱节点的next指针指向待删除节点的next,再释放待删除节点内存
  • 遍历结束未找到匹配节点时返回未找到提示

代码修改步骤

第一步:新增删除函数

在你现有printlist函数的下方新增删除功能函数:

// 参数使用node*&是因为删除头节点时需要修改原head指针的指向
void deleteNodeByIndcode(node*& head, int targetIndcode) {
    // 链表为空直接返回
    if (head == nullptr) {
        cout << "当前链表为空,无法删除节点" << endl;
        return;
    }
    node* temp = head;
    node* prev = nullptr;
    // 匹配头节点的情况
    if (temp != nullptr && temp->indcode == targetIndcode) {
        head = temp->next;
        delete temp;
        cout << "已成功删除indcode为" << targetIndcode << "的节点" << endl;
        return;
    }
    // 遍历查找待删除节点的前驱节点
    while (temp != nullptr && temp->indcode != targetIndcode) {
        prev = temp;
        temp = temp->next;
    }
    // 未找到匹配节点
    if (temp == nullptr) {
        cout << "未找到indcode为" << targetIndcode << "的节点,删除失败" << endl;
        return;
    }
    // 移除节点并释放内存
    prev->next = temp->next;
    delete temp;
    cout << "已成功删除indcode为" << targetIndcode << "的节点" << endl;
}

第二步:在main函数中新增删除交互逻辑

在main函数中printlist(head);(新增节点完成后的打印语句)之后、return 0;之前添加如下代码:

int delIndcode;
cout << endl << "请输入要删除节点的indcode(输入-1跳过删除操作):";
cin >> delIndcode;
while (delIndcode != -1) {
    deleteNodeByIndcode(head, delIndcode);
    cout << endl << "删除后的链表内容:" << endl;
    printlist(head);
    cout << endl << "请输入要删除节点的indcode(输入-1结束删除操作):";
    cin >> delIndcode;
}

注意事项

  • 如果需要按其他字段删除,只需要修改删除函数内的匹配判断条件即可
  • 代码中每次删除节点都主动调用delete释放内存,避免出现内存泄漏
  • 新增代码完全兼容你原有已实现的新增、打印逻辑,不需要修改原有功能代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:24:03