A Better version passing all the test cases of Leetcode:
ListNode *curr = head;
ListNode *next_head = curr->next;
ListNode *prev = NULL;
bool performDeletion = false;

while(next_head != NULL && curr != NULL) { if(next_head != NULL && curr != NULL && next_head->val != curr->val) { prev = curr; curr = curr->next; next_head = next_head -> next; } else if(next_head != NULL && curr != NULL && next_head->val == curr->val) { if(prev == NULL || prev == curr) { while(next_head != NULL && next_head->val == curr->val) { next_head = next_head->next; } head = next_head; prev = next_head; curr = next_head; if(next_head != NULL) next_head = next_head->next; else { head = NULL; break; } } else { while(next_head != NULL && next_head->val == curr->val) { performDeletion = true; next_head = next_head->next; } if(next_head == NULL) { if(prev == curr && performDeletion) head = NULL; else { prev->next = NULL; curr = NULL; } } else { prev->next = next_head; curr = next_head; next_head = next_head->next; } } } performDeletion = false; } return head; }