C++链表findEl函数返回异常,节点查找结果不符求助
链表查找函数
findEl逻辑错误修复 问题现象
- 构建了包含两个节点的链表:首节点对应字符数组
a(值为"Artifact"),第二个节点对应字符数组p(值为"Power") - 调用
findEl查找a对应节点时,程序无输出;查找p对应节点时,错误返回a对应的节点 - 作业要求必须使用
cstring库
错误原因
原findEl函数存在逻辑冗余与判断混乱:
- 函数开头单独判断头节点是否匹配,若不匹配进入else分支后,循环依然从头节点开始遍历,导致重复判断
- 冗余的分支逻辑引发遍历混乱,出现匹配错误或无输出的情况
修复方案
简化findEl的遍历逻辑,直接从头节点开始遍历整个链表,无需额外分支判断:
p_elements findEl(p_elements &p, char element[50]){ p_elements x = p; while(x != NULL){ if(strcmp(x->element, element) == 0){ return x; } x = x->next; } return NULL; }
同时修正main函数中的内存泄漏问题(原代码先分配节点再赋值为NULL),并添加空指针判断避免程序崩溃。
完整修正代码
#include <iostream> #include <cstdlib> #include <cstring> using namespace std; struct gameElements { char element[50]; char power[50]; int coordinates[2][2]; int pcoordinates[3][2]; gameElements *next; }; using p_elements = gameElements*; p_elements test(p_elements &p, char element[50], int parr[3][2], int x, int y) { p_elements newEl = new gameElements; strcpy(newEl->element, element); newEl->coordinates[0][0] = y; newEl->coordinates[0][1] = x; newEl->coordinates[1][0] = y; newEl->coordinates[1][1] = x + 1; newEl->next = NULL; for (int n = 0; n < 3; n++) { for (int i = 0; i < 2; i++) { newEl->pcoordinates[n][i] = parr[n][i]; } } if (p == NULL) { p = newEl; } else { p_elements tmp = p; while (tmp->next != NULL) { tmp = tmp->next; } tmp->next = newEl; } return p; } p_elements findEl(p_elements &p, char element[50]){ p_elements x = p; while(x != NULL){ if(strcmp(x->element, element) == 0){ return x; } x = x->next; } return NULL; } int main() { p_elements elements = NULL; char p[50] = "Power"; char a[50] = "Artifact"; int doorTonlvl[3][2] = { { 5, 96 }, { 6, 96 }, { 7, 96 } }; int vDoor[3][2] = { { 11, 54 }, { 12, 54 }, { 13, 54 } }; elements = test(elements, a, doorTonlvl, 4, 3); elements = test(elements, p, vDoor, 57, 8); p_elements artifact = findEl(elements, a); if(artifact != NULL){ cout << artifact->element << endl; } p_elements power = findEl(elements, p); if(power != NULL){ cout << power->element << endl; } return 0; }
修复效果
- 查找
a节点时,遍历到首节点匹配后返回,正常输出Artifact - 查找
p节点时,遍历到第二个节点匹配后返回,正常输出Power
内容的提问来源于stack exchange,提问作者helper
相关产品推荐
相关产品推荐

