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

C++链表删除函数无法删除首个节点问题求助

链表删除首个节点失败的问题解决

嘿,我一眼就发现问题所在啦!你的deleteStudent函数从链表的第二个节点开始遍历检查,完全没处理首个节点(也就是head指向的节点)的情况,这就是为啥删不了首节点的原因~

咱们拆解下原代码的核心问题:

  • 你初始化prev = head,current = head->next,直接跳过了第一个节点
  • 循环只检查current(也就是第二个及以后的节点),所以当要删除的是首节点时,循环根本不会触发,最后只会输出“找不到该值”

下面是修改后的代码,我专门加了对首节点的处理逻辑,还补了空链表的防崩溃检查:

void deleteStudent(){
    cout<<endl;
    cout<<"~DELETING A STUDENT~"<<endl;
    cout<<endl;
    string deletion;
    cout << "Enter student ID number: ";
    cin >> deletion;

    // 先处理首个节点的情况,同时避免空链表访问崩溃
    if (head != nullptr && head->studentNum == deletion) {
        student* temp = head;
        head = head->next; // 更新head指针到下一个节点
        delete temp;
        return;
    }

    // 处理第二个及以后的节点(沿用你原来的遍历逻辑)
    student *prev = head;
    // 这里也要加空判断,防止链表只有一个节点时访问head->next出错
    if (head == nullptr) {
        cout << "That value is not in the list" << endl;
        return;
    }
    student *current = head->next;
    while (current) {
        if (current->studentNum == deletion){
            prev->next = current->next;
            delete current;
            return;
        }
        prev = current;
        current = current->next;
    }

    cout << "That value is not in the list" << endl;
}

修改后就能正常处理首节点的删除了,同时也避免了空链表或单节点链表下的程序崩溃问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:58:01