链表环检测代码出现段错误,请求排查(GFG测试用例)
排查链表环检测代码的段错误原因
问题场景
在GeeksforGeeks的「Detect Loop in linked list」问题中,以下C++代码在执行指定测试用例时出现段错误:
测试用例说明
// 184 // 环所在节点的值
// 链表节点值序列:73 39 71 24 28 71 31 14 35 60 3 48 45 43 76 33 5 75 44 59 47 41 39 40 23 63 4 2 9 44 5 33 3 75 56 62 18 6 28 52 17 30 19 62 24 14 14 28 40 9 7 38 1 45 29 55 59 32 57 19 76 13 52 30 40 27 11 57 65 70 60 1 19 30 14 42 75 59 70 67 68 28 24 68 72 53 43 2 36 51 20 31 15 71 12 54 18 55 62 2 44 41 34 63 22 48 56 17 26 45 3 13 72 58 33 15 62 27 16 18 29 36 80 43 58 44 17 75 18 30 28 13 23 62 27 44 61 3 12 6 47 46 51 71 24 35 37 37 61 53 6 9 40 6 51 17 1 19 44 18 49 23 62 71 36 9 66 16 11 78 54 9 43 24 31 18 58 68 7 70 72 12 30 31
// 0 // 链表结束标识
出错代码
class Solution { public: //Function to check if the linked list has a loop. bool detectLoop(Node* head) { if(head->next ==NULL || head==NULL) { return false; } Node *slow=head; Node *fast=head; while(fast->next !=NULL && fast!=NULL) { slow=slow->next; fast=fast->next->next; if(slow==fast) {return true; } } return false; } };
错误原因分析
- 空指针访问顺序错误:开头判断
if(head->next ==NULL || head==NULL)逻辑颠倒,若head为空,先执行head->next会直接触发空指针解引用,导致段错误。 - 循环条件检查顺序错误:
while(fast->next !=NULL && fast!=NULL)中,若fast已为空,先访问fast->next会引发空指针访问。 - 循环内的空指针风险:即使
fast不为空,fast->next可能为空,此时执行fast->next->next会访问空指针的成员,触发段错误。
修复后的代码
class Solution { public: //Function to check if the linked list has a loop. bool detectLoop(Node* head) { // 先检查head是否为空,再检查next if(head == NULL || head->next == NULL) { return false; } Node *slow = head; Node *fast = head; // 先确保fast和fast->next不为空,再访问fast->next->next while(fast != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; if(slow == fast) { return true; } } return false; } };
内容的提问来源于stack exchange,提问作者Dhruv Mittal
相关产品推荐
相关产品推荐

