16 lines. Easy to understand and self-explained.


  • 0
    C
    public ListNode deleteDuplicates(ListNode head) {
        if(head==null) return head;
        int previous=head.val-1;
        ListNode fake=new ListNode(previous),safePlace=fake,temp=head; //safePlace means this is a actual distinct element
        while(temp!=null){
            if(temp.val==previous) safePlace.next=temp.next;
            else{
                safePlace.next=temp;
                previous=temp.val;
                if(temp.next==null||temp.next.val!=previous){
                    safePlace=temp;
                }
            }
            temp=temp.next;
        }
        return fake.next;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.