当前位置:   article > 正文

leetcode报错:member access within null pointer of type 'struct ListNode'

member access within null pointer

背景:在编写判断单链表是否有环时,出现这错误,


: 因为试图使用空指针
:增加判断条件,排除对空指针的引用。(一定要注意,我一直以为我排除了所有空指针的情况,其实并没有)


下面是报错的样例程序:

/**
 * 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 == NULL || head->next ==NULL)
        return false;
    ListNode* slow = head;
    ListNode* fast = head;
    while (slow!=NULL && fast->next != NULL)
    {
        //if (slow == NULL || fast->next == NULL)
        //  return false;
        slow = slow->next;
        fast = fast->next->next;

        if (slow == fast)
            return true;
    }
        return false;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

下面是修正过后的正确样例,区别在于while中的判断条件,此时判断条件排除了所有的空指针情况

/**
 * 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 == NULL || head->next ==NULL)
        return false;
    ListNode* slow = head;
    ListNode* fast = head;
    while (slow!=NULL && fast !=NULL &&fast->next != NULL)
    {
        //if (slow == NULL || fast->next == NULL)
        //  return false;
        slow = slow->next;
        fast = fast->next->next;

        if (slow == fast)
            return true;
    }
        return false;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/945571
推荐阅读
相关标签
  

闽ICP备14008679号