Deleting all the matching items in single linked list I have the following code which I implemented to delete all the nodes for the matching value. My code handles all the 63 varieties of test case scenarios including scenarios like deleting 1 from linked list 1->1, leaving the linked list empty.

  public ListNode RemoveElements(ListNode head, int val) {
      if(head != null)
    {
        ListNode current = head;
        ListNode prevNode;
        while(current !=null &amp;&amp; current.next != null)
        {
            prevNode = current;
            if(current.val == val)
            {
                current.val = current.next.val;
                current.next = current.next.next;
            }
            else
                current = current.next;
        }


        int count = 0;
        ListNode p = head;
        ListNode pBefore = null;
        while(p != null)
        {
            if(p.next != null)
                pBefore = p;
            p = p.next;
            count++;
                        }

        if(current.val == val)
        {
            if(count == 1)
             head = null;
             else if(count &gt; 1)
                pBefore.next = null;
        }

    }
    return head;     

}


I'm sure this can be optimized and it would be great if someone can share the best way to delete all the matching items in single linked list.

I tried searching on Google, but everywhere it is handled as part of a SingleLinked list custom class having head and tail node access. In my case, I am handling in a method and I have access only to the head of the list through the input parameter.
Several issues jump in the eyes:


very complicated logic
very strange "removal" logic: copy value from next node + delete next node
is recommended to use braces even on single statement if-else
messy indentation


This can be done a lot simpler, by using a dummy node:

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

ListNode runner = dummy;
while (runner.next != null)
{
    if (runner.next.val == val)
    {
        runner.next = runner.next.next;
    }
    else
    {
        runner = runner.next;
    }
}

return dummy.next;