YSMull
<-- algorithm



原题链接

遍历法

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode p = head;
        while (p != null) {
            if (p.next != null && p.next.val == p.val) {
                p.next = p.next.next; //注意,如果删除后不能让 p 后移
            } else {
                p = p.next;
            }
        }
        return head;
    }
}

递归法

定义子问题为链表的 tail 的去重问题。

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) return head;
        head.next = deleteDuplicates(head.next);
        if (head.val == head.next.val) {
            head.next = head.next.next;
        }
        return head;
    }
}