Home > database >  LeetCode - 203. Remove Linked list element. could you explain why my solution is not working please?
LeetCode - 203. Remove Linked list element. could you explain why my solution is not working please?

Time:07-24

I found the answer which uses the similar approach I am using. This is the correct answer.

    public static ListNode removeElements(ListNode head, int val) {
    ListNode temp = new ListNode(0);
    temp.next = head;
    ListNode prev = temp;
    while(head != null) {
        if(head.val == val) {
            prev.next = head.next;
        }
        else {
            prev = head;
        }
        head = head.next;
    }
    return temp.next;  
}

And I'll show you my answer first.

    public static ListNode removeElements_wrong(ListNode head, int val) {
    ListNode prev = new ListNode(0);
    prev.next = head;
    while(head != null) {
        if(head.val == val) {
            prev.next = head.next;
        }
        else {
            prev = head;
        }
        head = head.next;
    }
    return prev;  
}

When the inputs are [1,2,6,3,4,5,6], 6. output is [5] I see the differences is above the while loop and return statement. I directly set

ListNode prev = new ListNode(0);
prev.next = head;

But the correct solution has

ListNode temp = new ListNode(0);
temp.next = head;
ListNode prev = temp;

I don't understand why I need to use temp, how is it working and why can't I just set ListNode pre = 0 and pre.next=head. Then return prev?

Thank you

CodePudding user response:

You need to keep track of the prev in the temp variable because you are modifying the prev inside the while loop and lost the first state when temp and prev were pointing to.

As you noticed the temp is declared with a dummy node so when return just call temp.next

enter image description here

  • Related