082.Remove Duplicates from Sorted List II Posted on 2017-09-24 | In LeetCode Test cases1234567[][1,1][1,1,2][1,1,2,2][1,2,2,3][1,2,2,3,3][1,2,3,4,5] Solution 1: accepted 1msTry to use only ListNode 1234567891011121314151617181920212223242526public ListNode deleteDuplicates(ListNode head) { ListNode pointer = head; ListNode previous = null; while (pointer != null) { ListNode fast = pointer.next; boolean duplicate = false; while (fast != null && pointer.val == fast.val) { fast = fast.next; duplicate = true; } if (!duplicate) { previous = pointer; } else { if (previous == null) { // [1,1,...] head = fast; } else { previous.next = fast; // [1,2,2,3...] } } pointer = fast; } return head;} Solution 2: accepted 1msUse a virtual node to help organize the list 123456789101112131415161718public ListNode deleteDuplicates(ListNode head) { ListNode virtualHead = new ListNode(0); virtualHead.next = head; ListNode pre = virtualHead; ListNode cur = head; while (cur != null) { while (cur.next != null && cur.val == cur.next.val) { cur = cur.next; } if (pre.next == cur) { // if both pre and cur point to the same node (no duplicates detected) pre = cur; // simply move on } else { pre.next = cur.next; // skip points in between } cur = cur.next; // move on } return virtualHead.next;}