-
链接
https://leetcode.cn/problems/remove-duplicates-from-sorted-list/ -
题目
给定一个已排序的链表的头head, 删除所有重复的元素,使每个元素只出现一次 。返回已排序的链表 。
-
思路
代码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)
return head;
//1
ListNode* lead=head,*pre=head;
head=head->next;
while(head){
if(pre->val==head->val)
pre->next=head->next;
else
pre=head;
//当pre和head值不同时,pre才进行变化,不然,1,1]错误,pre和head只是前后值的比较,对于多个重复数操作不正确
head=head->next;
}
return lead;
//2,简化掉了pre!!
ListNode* cur=head;
//条件为cur->next,如果是cur,那么例子[1],if判断中cur->next->val引用空指针,会报错
while(cur->next){
if(cur->val==cur->next->val)
cur->next=cur->next->next;
else
cur=cur->next;
}
return head;
}
};