解题思路:
(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==NULL) return head;
ListNode *prev = head,*p=head->next;
while(p) {
if(p->val==prev->val) {
prev->next = p->next;
p = p->next;
} else {
prev = p;
p = p->next;
}
}
return head;
}
};