Why my solution will give a wrong answer for test case {1,1}


  • 2
    S

    public class Solution {

    public ListNode deleteDuplicates(ListNode head) {
    
        if (head == null || head.next == null || head.next.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(Integer.MIN_VALUE);
        dummy.next = head;
        ListNode pre = dummy;
        ListNode next = pre.next;
        while (next != null) {
            if (pre.val == next.val) {
                pre.next = next.next;
                next = pre.next;
                continue;
            }else {
                pre = pre.next;
                next = next.next;
                continue;
            }
        }
        return dummy.next;
    }
    

    }


  • 0
    B

    Because when "head. next.next == null", your program simply returns the head. It should be fine if you just use "if(head == null) return head;"
    Also, "continue" may be unnecessary.


  • 0
    V

    If the input ListNode contains one or no elements then need to return the list as there cannot be any duplicates to remove, but if the linked list has two elements then there can be duplicates hence the condition
    head->next->next ==null shouldn't be checked as it leads to output the duplicated elements List.

    public class Solution{
    public ListNode deleteDuplicates(ListNode head) {
    
        if (head == null || head.next == null ) {
            return head;
        }
        ListNode dummy = new ListNode(Integer.MIN_VALUE);
        dummy.next = head;
        ListNode pre = dummy;
        ListNode next = pre.next;
        while (next != null) {
            if (pre.val == next.val) {
                pre.next = next.next;
                next = pre.next;
                continue;
            }else {
                pre = pre.next;
                next = next.next;
                continue;
            }
        }
        return dummy.next;
    }
    }

Log in to reply
 

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