【力扣 007】 83. 删除排序链表中的重复元素
83. 删除排序链表中的重复元素
解法1:
/**
* 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;
ListNode *dumy = new ListNode(-1), *pre = dumy;
dumy->next = head;
ListNode *p = head;
while(p)
{
while(p->next && p->val == p->next->val)
p = p->next;
if(pre->next == p)
{
pre = p;
p = p->next;
}
else
{
pre->next = p;
pre = pre->next;
p = p->next;
}
}
return dumy->next;
}
};