Need help, can't figure out what's wrong with this java code.


  • 0
    V

    This cod can't pass the test case [1,1], output is still [1, 1], but I cant figure out why output is not [].

    public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null || head.next.next == null){
            return head;
        }
        ListNode dummy = new ListNode(1);
        dummy.next = head;
        ListNode p = dummy;
        ListNode x = p.next;
        ListNode y = p.next.next;
        
        while(x != null && y != null){
            if(x.val != y.val){
                p = p.next;
                x = p.next;
                y = x.next;
            }else{
                while(y != null && x.val == y.val){
                    y = y.next;
                }
                
                if(y == null){
                    p.next = null;
                    return dummy.next;
                }else{
                    p.next = y;
                    x = p.next;
                    y = y.next;
                }
            }
        }
        
        return dummy.next;
    }

  • 0
    M

    ur code will note pass test case [1,1] coz of ur first if condition head.next.next == null

    means code will not check arrays of size 2


  • 0
    L

    Should use a flag to tell if have met the same value before or not.


  • 0
    L

    If exist duplicate nodes at beginning of the NodeList, head should be pointed to new position, like "head==new", other pointers which point to head moving has no effect.


Log in to reply
 

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