My Accepted Iterative Version of Code in Java (With Explanation)


  • 0
    F
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null){
            return null;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode prev = dummy;
        
        while (head!= null && head.next != null){
            if (head.val == head.next.val){
                while (head.next != null && head.val == head.next.val){
                    head = head.next;
                }
                
                prev.next = head.next;
                head = head.next;
            }else{
                head = head.next;
                prev = prev.next;
            }
        }
        
        return dummy.next;
    }
    

    Case1: if duplication exists, find the first node which has different value, set the prev.next to be this node.
    Case2: If not duplicate, move to the next node.


Log in to reply
 

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