自己想到的是三指针解法,自己倒是没想到递归解。

三指针:

public class Solution {
    public ListNode deleteDuplication(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode h = new ListNode(-1); // 头结点,用于返回结果
        h.next = head;
        ListNode pre = h, cur = head, next; // 三指针
        while (cur != null && cur.next != null) {
            next = cur.next;
            if (cur.val == next.val) {
                while (next != null && next.val == cur.val) {
                    next = next.next;
                }
                pre.next = next;
                cur = pre.next;
            } else {
                pre = cur;
                cur = next;
            }
        }
        return h.next;
    }
}

排行榜里面的递归解太巧妙了,这里学习记录:

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

        ListNode next = head.next;
        if (head.val == next.val) { // 重复发生在起始节点的时候
            while (next != null && head.val == next.val) {
                next = next.next;
            }
            return deleteDuplication(next);
        } else {
            // 起始节点没有重复的时候
            head.next = deleteDuplication(head.next);
            return head;
        }
    }
}