ランタイムエラー:タイプ 'struct ListNode'(solution.cpp)エラーのnullポインター内のメンバーアクセス
Runtime Error Member Access Within Null Pointer Typestruct Listnode Solution
エラーコード:
/*The use code is leetcode141-circular linked list*/ /** * Definition for singly-linked list. * struct ListNode { * int val * ListNode *next * ListNode(int x) : val(x), next(NULL) {} * } */ class Solution { public: bool hasCycle(ListNode *head) { if(!head||!head->next) return false ListNode *slow=head,*fast=head->next while(slow!=fast){ if(!slow||!fast){/*There was an error in this step*/ return false } slow=slow->next fast=fast->next->next } return true } }
エラーの場所: if(!slow||!fast){/*There is an error in this step*/
理由:
fast=fast->next->next
fast-> nextが空の場合、上記のステートメントは実際にはfast = null-> nextであり、現在のfastでnull操作if(!slow ||!fast)を実行するとエラーが発生します。
/** * Definition for singly-linked list. * struct ListNode { * int val * ListNode *next * ListNode(int x) : val(x), next(NULL) {} * } */ class Solution { public: bool hasCycle(ListNode *head) { if(!head||!head->next) return false ListNode *slow=head,*fast=head->next while(slow!=fast){ if(!slow||!fast||!fast->next){/*Add a blank for fast->next*/ return false } slow=slow->next fast=fast->next->next } return true } }