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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29007291/article/details/82184134

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


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


下面是报错的样例程序:

/**
 * 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;
    }
};

下面是修正过后的正确样例,区别在于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;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_29007291/article/details/82184134