# [leetcode题解]82.Remove Duplicates from Sorted List-II(排序链表保留唯一)

Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

c++代码：

```class Solution {
public:
ListNode* deleteDuplicates(ListNode* head)
{
if (head == NULL)return head;

ListNode *pre = new ListNode(-1);
pre->next = NULL;

ListNode *p = head, *tail = pre, *q = NULL;
while(p!= NULL)
{
//先看下是否相同
q = p->next;
if (q == NULL || q->val != p->val)
{
tail->next = p;
tail = tail->next;
p = q;
continue;
}
//如果相同，则一直找到不同元素为止
while(q != NULL && q->val == p->val)q = q->next;
p = q;
}
tail->next = NULL;
return pre->next;
}
};```

python代码：

```class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
:author: 凌风技术站-iaccepted
"""
if head is None:
return head

pre = ListNode(-1)
tail = pre

#把所有唯一出现的节点插入一个新链表中即可
q = head
while q is not None:
#下面找当前节点q及后续节点有几个值是相同的
n = 0
p = q
while p is not None and p.val == q.val:
p = p.next
n += 1

#若n=1，则说明当前节点的值唯一
if n == 1:
tail.next = q
tail = q
q = p
tail.next = None
return pre.next```