# 82. Remove Duplicates from Sorted List II 删除排序链表中的重复元素 II

## # 题目描述

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

``````Input: 1->2->3->3->4->4->5
Output: 1->2->5
``````

Example 2:

``````Input: 1->1->1->2->3
Output: 2->3
``````

## # 解题方法

### # 递归

``````/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
}
} else {
while (move && head->val == move->val) {
move = move->next;
}
return deleteDuplicates(move);
}
}
};
``````

### # 遍历

``````1. 1(pre,pre->next=2)->2(cur)->3->3->4->4->5
2. 1->2(pre,pre->next=4)->3->3(cur)->4->4->5
3. 1->2(pre,pre->next=5)->3->3->4->4(cur)->5
4. 1->2(pre,pre->next=None)->3->3->4->4->5(cur)
5. 1->2->3->3->4->4->5(pre,pre->next=None)(cur=None)
``````

C++代码如下：

``````/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
while (cur) {
//跳过当前的重复节点，使得cur指向当前重复元素的最后一个位置
while (cur->next && cur->val == cur->next->val) {
cur = cur->next;
}
if (pre->next == cur) {
//pre和cur之间没有重复节点，pre后移
pre = pre->next;
} else {
//pre->next指向cur的下一个位置（相当于跳过了当前的重复元素）
//但是pre不移动，仍然指向之前的链表结尾
pre->next = cur->next;
}
cur = cur->next;
}
}
};
``````

### # 字典统计次数

python代码如下：

``````# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
"""
:rtype: ListNode
"""
root = ListNode(0)
val_list = []
counter = collections.Counter(val_list)
else:
return root.next
``````

C++代码如下：

``````/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
unordered_map<int, int> m;
ListNode dummy(0);
ListNode* dummy_move = &dummy;
while (move) {
m[move->val]++;
move = move->next;
}
while (move) {
if (m[move->val] == 1) {
dummy_move->next = move;
dummy_move = dummy_move->next;
}
move = move->next;
}
dummy_move->next = nullptr;
return dummy.next;
}
};
``````

## # 日期

2018 年 6 月 23 日 ———— 美好的周末要从刷题开始