[leetcode] 82. 删除排序链表中的重复元素 II

82. 删除排序链表中的重复元素 II

83题的扩展,相比于83题。我们增加一个last_last来记录重复元素前面的节点即可

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null) return head;
        if (head.next == null) return head;
        ListNode now = head.next;
        ListNode last = head;
        ListNode last_last = null;
        while (now != null) {
            if (now.val == last.val) {
                while (now != null && now.val == last.val) {
                    now = now.next;
                }
                if (last_last != null) last_last.next = now;
                else {
                    head = now;
                }
            } else
                last_last = last;
            last = now;
            if (now != null)
                now = now.next;
        }
        return head;
    }
}
posted @ 2018-07-30 17:06  ACBingo  阅读(223)  评论(0编辑  收藏  举报