C++链表删除价格超指定值元素异常问题修复求助
问题分析与修复方案
你的代码出现“删除所有头插元素”的问题,核心有两个原因:
- 删除函数
del_el会遍历整个链表,删除所有价格大于b的元素,而非仅删除一个; - 函数内硬编码了
b=100,忽略传入参数,且main函数调用时b未初始化,导致逻辑完全不受控。
此外还有打印函数逻辑错误、全局数组设计冗余等次要问题,下面逐个修复:
修复步骤
1. 修正删除逻辑:仅删除第一个符合条件的元素
当前del_el的循环会遍历全链表删除所有超标元素,要实现“仅删一个”,找到第一个符合条件的元素后,删除并立即退出循环即可。
2. 移除硬编码的b值,让用户输入指定阈值
删除del_el里的b=100赋值,在main函数调用删除功能前,让用户输入价格阈值b,避免使用未初始化变量。
3. 修复打印函数的逻辑错误
原print_list的嵌套for循环会强制遍历n个节点,链表长度变化后易触发空指针访问,改为直接遍历链表到末尾,再按需打印其他元素。
4. 优化冗余的全局数组与add_eq函数
原全局数组eq和add_eq与链表分离,设计冗余,若无需单独维护可直接移除;若需保留,可简化add_eq的参数逻辑。
修复后的完整代码
#include <iostream> #include <cstring> #include <fstream> #include <list> using namespace std; struct Equipment { char name[20]; double price; char date[20]; Equipment* next; }; void add_el_beg(Equipment*& head, int n) { for (int i = 0; i < n; i++) { Equipment* new_el_beg = new Equipment; cout << "Enter the name of eq: " << endl; cin >> new_el_beg->name; cout << "Enter the price of eq: " << endl; cin >> new_el_beg->price; cout << "Enter the date of eq: " << endl; cin >> new_el_beg->date; new_el_beg->next = head; head = new_el_beg; cout << "Інструмент було успішно додано в список. " << endl; } } void print_list(Equipment* head) { Equipment* current = head; cout << "链表元素:" << endl; while (current != nullptr) { cout << current->name << " " << current->price << " " << current->date << endl; current = current->next; } // 若需打印原全局数组eq的元素,可在此添加对应逻辑 } void del_el(Equipment*& head, int& n, double b) { Equipment* current = head; Equipment* prev = nullptr; while (current != nullptr) { if (current->price > b) { if (prev == nullptr) { // 删除头节点 head = current->next; delete current; current = head; } else { // 删除中间/尾节点 prev->next = current->next; delete current; current = prev->next; } n--; // 找到第一个符合条件的元素后退出循环,实现仅删除一个 break; } else { prev = current; current = current->next; } } // 打印删除后的链表 cout << "删除后的链表:" << endl; current = head; while (current != nullptr) { cout << current->name << " " << current->price << " " << current->date << endl; current = current->next; } } int main() { int n, c = 7; double b; Equipment* head = nullptr; cout << "Enter the number of eq to add at beginning: " << endl; cin >> n; while (c != 6) { cout << "Enter your option (1-5): "; cin >> c; switch (c) { case 1: add_el_beg(head, n); break; case 2: print_list(head); break; case 3: cout << "Enter the price threshold b: " << endl; cin >> b; del_el(head, n, b); break; default: cout << "Wrong!" << endl; break; } } // 释放链表内存,避免内存泄漏 Equipment* temp; while (head != nullptr) { temp = head; head = head->next; delete temp; } return 0; }
额外说明
- 如果需求是删除所有价格大于b的元素,只需去掉
del_el函数里的break语句即可; - 修复后的代码移除了冗余的全局数组
eq和add_eq函数,若有特殊需求可自行恢复,但建议尽量用链表统一管理元素; - 新增了链表内存释放逻辑,避免程序结束后内存泄漏。
内容的提问来源于stack exchange,提问作者Lvrnnk
相关产品推荐
相关产品推荐

