My recursive Java solution without dummy head


  • 0
    T
        Integer last = null; // remember the last duplicate found
    
        public ListNode deleteDuplicates(ListNode head) {
            if (head == null)
                return null;
            head.next = deleteDuplicates(head.next);
    
            // this value equals to the next value, duplicates found. update 'last'.
            if (head.next != null && head.next.val == head.val) {
                last = head.val;
                return head.next.next;
            }
    
            // if this value equals to the last value.
            if (last != null && head.val == last) {
                return head.next;
            }
            return head;
        }
    

Log in to reply
 

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