思路:
删除排序链表的重复结点是要求删除其他重复的,只留下一个值相同的结点。而这题要求把所有与重复值相同的都删掉,一个不留!所以我们要设立pre指针作为前驱,并设置哑结点指向表头,pre从哑结点开始遍历链表,若有重复值,就操作删除pre的后继结点和后继结点的后继。
tips:循环条件一定要注意判空,不然就会出现Line 19: Char 34: runtime error: member access within null pointer of type 'ListNode' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:28:34这种报错信息,原因是出现野指针。
具体代码及注释如下:
/**
* 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) {
ListNode*dummy=new ListNode;dummy->next=head;//创建哑结点
ListNode*pre=dummy;
while(pre->next&&pre->next->next){//从头遍历
if(pre->next->val==pre->next->next->val){
int x=pre->next->val;//记录重复的值
while(pre->next&&pre->next->val==x)//注意这里必须判空条件!
{pre->next=pre->next->next;}//删除一个重复的结点
}
else{pre=pre->next;}//没重复就往前走
}
return dummy->next;//返回有效的第一个结点
}
};