Sunday, February 9, 2014

Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

Solution:
Is it assumes that the linked list has been sorted?
If yes, then it is trivial.

public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummy = new ListNode(0);
        ListNode prev = dummy;
        ListNode cur = head;
        
        while(cur != null){

            // there are duplicates
            if(cur != null && cur.next != null && cur.val == cur.next.val){
                int value = cur.val;
                while(cur != null && cur.val == value)
                    cur = cur.next;
                    
                prev.next = cur;
            }

            // there is no duplicates
            else{
                prev.next = cur;
                prev = cur;
                cur = cur.next;
            }
        }
        
        return dummy.next;
    }
}

No comments:

Post a Comment