Monday, December 8, 2014

Remove duplicate from sorted list LeetCode

Check whether the duplicate is existing or not.
If so, prev.next = curr.next. If not, prev.next = curr;

 public ListNode deleteDuplicates(ListNode head) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if (head == null) return null;
        ListNode dummy = new ListNode(-1);
        dummy.next =head;
        ListNode prev = dummy;
        ListNode curr = head;
       
        while (null != curr) {
            while (curr.next != null && prev.next.val == curr.next.val) {
                curr = curr.next;
            }
           
            if (prev.next == curr) {
                prev = curr;
            } else {
                prev.next = curr.next;
            }
            curr = curr.next;
        }
        return dummy.next;

    }

No comments:

Post a Comment