package fundamentals.list.removal.lc203_removelinkedlistelements;

import fundamentals.list.ListNode;

/**
 * Remove all elements from a linked list of integers that have value val.
 * Example:
 *  Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
 *  Return: 1 --> 2 --> 3 --> 4 --> 5
 */
public class Solution {

    public ListNode removeElements(ListNode head, int val) {
        if (head == null) {
            return null;
        }

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

        ListNode prev = dummy;
        while (prev.next != null) {
            if (prev.next.val == val) {
                prev.next = prev.next.next; // prev remains, so it cannot be null
            } else {
                prev = prev.next;           // prev.next is non-null, so prev cannot be null
            }
        }
        return dummy.next;
    }

    // My 1st
    public ListNode removeElements1(ListNode head, int val) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;

        ListNode prev = dummy;
        while (prev.next != null) {
            if (prev.next.val == val) {
                prev.next = prev.next.next;
            } else {    // error: move only when next node is not deleted, otherwise NPE...
                prev = prev.next;
            }
        }
        return dummy.next;
    }

}

@@ -365,32 +365,395 @@
 ead, int val) %7B%0A
+        ListNode dmy = new ListNode(0), pre = dmy;%0A        dmy.next = head;%0A        while (pre.next != null) %7B%0A            if (pre.next.val == val) %7B%0A                pre.next = pre.next.next;%0A            %7D else %7B%0A                pre = pre.next;%0A            %7D%0A        %7D%0A        return dmy.next;%0A    %7D%0A%0A    public ListNode removeElements2(ListNode head, int val) %7B%0A
         if (head

remove linked list elements