Wrong topic: delete duplicate elements in the sorted list
例如 1->1->2
输出 1->2
The cause of the error: Trying to use a null pointer.
Solution: Increase the judgment condition, and the order of judgment cannot be changed. Exclude references to null pointers.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
/* if (head == nullptr || head->next == nullptr) {
return head;
}*/
if (head->next == nullptr || head == nullptr) {
return head;
}
ListNode* cur = head->next;
ListNode* node = head;
while (cur != nullptr) {
if (cur->val == node->val) {
node->next = cur->next;
cur = cur->next;
}
else {
cur = cur->next;
node = node->next;
}
}
return head;
}
};
The above code seems to be logically correct, but when judging a null pointer, an error is reported.
The error is this paragraph:
runtime error: member access within null pointer of type 'struct ListNode'
The meaning of this sentence is to try to use a null pointer. An error occurred when judging the following statement.
if (head->next == nullptr || head == nullptr)
We can see that if it head
is a null pointer, it head->next
is illegal in itself, so an error will be reported, but if we change the order, it will be correct
if (head == nullptr || head->next == nullptr)
.
This is a mistake when doing the question, I hope it can be remembered.