给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
示例 1:
输入:head = [1,1,2]
输出:[1,2]
示例 2:
题目很简单,但是写出来一直报错
Line 26: Char 15: runtime error: member access within null pointer of type 'ListNode' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:35:15
因为需要注意判断head是否为空,如果为空还继续访问,就会引起空指针访问错误。
/**
* 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为空时,如果继续访问,则会引起访问空指针错误
return nullptr;
ListNode* fast=head;
ListNode* slow=head;
while(fast)
{
if(fast->val!=slow->val)
{
slow->next=fast;
slow=slow->next;
}
fast=fast->next;
}
slow->next=nullptr;
return head;
}
};