way 1, with sentinent or nullNode approach, shrinks partial cases
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode RemoveElements(ListNode head, int val) {
if (head == null)
return null;
ListNode nullNode = new ListNode();
nullNode.next = head;
ListNode current = nullNode;
// start node and middle
while (current.next.next != null) {
if (current.next.val == val) {
current.next = current.next.next;
continue;
}
current = current.next;
}
// last node
if (current.next.val == val)
current.next = null;
return nullNode.next;
}
}
way2, more partial cases
public ListNode RemoveElements(ListNode head, int val)
{
if (head == null)
return null;
ListNode res = head;
ListNode current = head;
ListNode previous = null;
bool wasDeletedFromMiddle = false;
while (current != null)
{
if (current.val == val)
{
// head
if (current == head)
{
head = head.next;
res = head;
}
// body
else if (current != head && current.next != null)
{
if (current.next != null && current.next.val == val)
{
current = current.next;
continue;
}
previous.next = current.next;
}
// tail
else if (current != head && current.next == null)
{
previous.next = null;
}
}
previous = current;
current = current.next;
}
return res;
}