2

I don't know why the result of subit is "member access within null pointer of type 'struct ListNode'". I tested the sample and the capital was correct, I don't know what is wrong with my cognition of the empty indicators, can someone help me?

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* deleteDuplicates(struct ListNode* head){
   
    struct ListNode* node = head;
    while(node->next != NULL && node != NULL){
        if(node->val == node->next->val){
            struct ListNode* duplicate = node->next;
            node->next = node->next->next;
            free(duplicate);
        }
        else node = node->next;
    }
    return head;
}

1 Answer 1

1

If the list is empty head will be NULL. In the while loop expression node is dereferenced using node->next which is evaluated before the right hand side, which checks node for NULL. You should check to see if node is NULL before evaluating the while loop and NULL checks for node should always be performed before NULL checks for node->next.

This would be my suggestion:

struct ListNode* deleteDuplicates(struct ListNode* head){
   
    struct ListNode* node = head;
    while(node != NULL){
        if(node->next == NULL)
        {
           node = node->next;
        }
        else if(node->val == node->next->val){
            struct ListNode* duplicate = node->next;
            node->next = node->next->next;
            free(duplicate);
        }
        else node = node->next;
    }
    return head;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much!I’m very grateful for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.