Remove Duplicates from Sorted List II

This is No.82. in leetcode.

My code is given below:

/**
 * 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) {

        if(head == null || head.next == null){
            return head;
        }

        ListNode start = new ListNode(-1);
        ListNode pre = start;
        start.next = head;

        while(pre.next != null){
            ListNode post = pre.next;

            // collect all duplicate nodes
            while((post.next != null) && (post.val == post.next.val)){
                post = post.next;
            }

            // move pre
            if(pre.next == post){
                pre = pre.next;
            }

            else{
                pre.next = post.next;
            }
        }

        return start.next;
    }
}

I think the most important point is that I need to build a dummy node at the beginning of linked list, because we have to consider the case which the duplicate nodes occur in the beginning. And also I should pay attention on when and how move "pre" and "post" node.

Leave a Reply