C++非顺序链表元素对比异常:Different列表内容错误求助
问题排查与修复
核心问题点
Identical函数逻辑完全偏离需求:这个函数本该用来判断「单个元素是否存在于另一链表」,但当前实现的是「两个链表是否按顺序完全一致」,完全没用在点上。- 遍历A链表时未处理当前元素:主函数里用
tmp遍历A,但每次调用Identical传的都是整个链表A,而且判断条件错误,导致反复把A的第一个元素塞进Different链表。 - 遗漏B链表独有的元素:原代码只处理了A的部分,没把B中不在A里的元素加入Different。
修复后的完整代码
#include <fstream> #include <iostream> // 补充ListItem结构体定义(原代码未给出) struct ListItem { int data; ListItem* next; ListItem(int val) : data(val), next(nullptr) {} }; // 向链表尾部添加元素 void Add(ListItem** head, int x) { ListItem* newNode = new ListItem(x); if (*head == nullptr) { *head = newNode; return; } ListItem* tmp = *head; while (tmp->next != nullptr) { tmp = tmp->next; } tmp->next = newNode; } // 打印链表内容 void Print(ListItem** head) { ListItem* tmp = *head; while (tmp != nullptr) { std::cout << tmp->data << " "; tmp = tmp->next; } std::cout << std::endl; } // 返回分隔线(原代码未给出,补充实现) std::string Sep() { return "------------------------"; } // 新增:判断单个元素是否存在于目标链表中 bool IsElementPresent(ListItem* head, int target) { ListItem* tmp = head; while (tmp != nullptr) { if (tmp->data == target) { return true; } tmp = tmp->next; } return false; } int main() { ListItem* A = nullptr; ListItem* B = nullptr; ListItem* Different = nullptr; std::ifstream file("liczby.txt", std::fstream::in); bool write = true; int x; while (file >> x) { if (write) { Add(&A, x); } else { Add(&B, x); } write = !write; } std::cout << "List A: " << std::endl; Print(&A); std::cout << Sep() << std::endl; std::cout << "List B: " << std::endl; Print(&B); std::cout << Sep() << std::endl; // 收集A中独有的元素 ListItem* tmpA = A; while (tmpA != nullptr) { if (!IsElementPresent(B, tmpA->data)) { Add(&Different, tmpA->data); } tmpA = tmpA->next; } // 收集B中独有的元素 ListItem* tmpB = B; while (tmpB != nullptr) { if (!IsElementPresent(A, tmpB->data)) { Add(&Different, tmpB->data); } tmpB = tmpB->next; } std::cout << "List Different: " << std::endl; Print(&Different); std::cout << Sep() << std::endl; // 正确释放链表内存(避免泄漏) auto deleteList = [](ListItem*& head) { ListItem* tmp; while (head != nullptr) { tmp = head; head = head->next; delete tmp; } }; deleteList(A); deleteList(B); deleteList(Different); return 0; }
关键修改说明
- 新增
IsElementPresent函数:这是实现需求的核心,专门用来检查单个元素是否存在于目标链表中。 - 修正A链表遍历逻辑:用
tmpA逐个遍历A的元素,每次检查当前元素是否不在B中,符合条件就加入Different。 - 补充B链表的处理:同样遍历B的元素,把不在A中的元素也加入Different,确保所有独有的元素都被收集。
- 修复内存释放:原代码直接
delete A只会释放头节点,新增的deleteList会逐个释放链表的所有节点,避免内存泄漏。 - 修正变量名拼写:把
Diffrent改成Different,符合英文拼写规范。
内容的提问来源于stack exchange,提问作者D08R0
相关产品推荐
相关产品推荐

