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 && 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 > 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.