错误题目:删除排序链表中的重复元素
例如 1->1->2
输出 1->2
错误原因:试图使用空指针
解决方法:增加判断条件,并且判断的顺序不能改变。排除对空指针的引用。
/**
* 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;
}
};
上面的代码看上去逻辑上是没有错误的,但是在判断空指针的时候,报错。
报错是这样一段话:
runtime error: member access within null pointer of type 'struct ListNode'
这句话的意思就是,试图使用空指针。在判断如下语句时候出现错误。
if (head->next == nullptr || head == nullptr)
我们可以看到,假如head
是空指针的话,那么head->next
本身是不合法,因此会报错,但是我们如果把顺序改一下就没错了
if (head == nullptr || head->next == nullptr)
。
这是做题时候的一个错误,希望可以记住。