目录
82. 删除排序链表中的重复元素 II
题目描述:
实现代码与解析:
链表遍历:
实现代码与解析:
82. 删除排序链表中的重复元素 II
题目描述:
        给定一个已排序的链表的头 head , 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。
示例 1:

输入:head = [1,2,3,3,4,4,5] 输出:[1,2,5]
示例 2:

输入:head = [1,1,1,2,3] 输出:[2,3]
提示:
- 链表中节点数目在范围 
[0, 300]内 -100 <= Node.val <= 100- 题目数据保证链表已经按升序 排列
 
实现代码与解析:
链表遍历:
C++
/**
 * 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) {
        
        ListNode* dummy = new ListNode();
        dummy->next = head;
       
        ListNode* cur = dummy;
        while (cur->next && cur->next->next) {
            if (cur->next->val == cur->next->next->val) {
                int t = cur->next->val; // 可能不止一个相同的,记录下来再找
                while (cur->next && cur->next->val == t) {
                    cur->next = cur->next->next;
                }
            } else {
                cur = cur->next;
            }
        }
        return dummy->next;
    }
}; 
 
java
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        
        ListNode dummy = new ListNode();
        dummy.next = head;
        ListNode cur = dummy;
        while (cur.next != null && cur.next.next != null) {
            if (cur.next.val == cur.next.next.val) {
                int t = cur.next.val;
                while (cur.next != null && cur.next.val == t) {
                    cur.next = cur.next.next;
                }
            } else {
                cur = cur.next;
            }
        }
        return dummy.next;
    }
} 
实现代码与解析:
首先,这种链表题一般都要创建一个虚拟头节点,dummy,因为它给的头节点可能也是需要删除的,定义了虚拟头节点这样代码好写,不用再考虑那么多极限情况,遍历起来也方便。
给定的链表是有序的,考虑到重复的都需要删除,而不是留一个,所以,我们需要同时遍历三个节点,后两个用于遍历对比,前一个用来执行不需要删除的节点。
如果找到了相同节点,注意重复的节点可能不止只有两个,所以要用while持续判断,同时改变节点的指向。
注意,最后返回的是dummy节点的下一个节点,而不是head,可能head已经逻辑上删除了。



















