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
相关产品推荐
相关产品推荐

