link

node, create a dummy node because the head node may be the target value ; and be VERY aware of corner case, so we need to consider cur and cur.next edge cases to consider :

  1. The linked list is empty, i.e. the head node is None.
  2. Multiple nodes with the target value in a row.
  3. The head node has the target value.
  4. The head node, and any number of nodes immediately after it have the target value.
  5. All of the nodes have the target value.
  6. The last node has the target value.
    #time O(N) spaceO(1)
    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, val=0, next=None):
    #         self.val = val
    #         self.next = next
    class Solution:
     def removeElements(self, head: ListNode, val: int) -> ListNode:
         dummy = ListNode(-1)
         dummy.next = head
         cur = dummy
         while cur and cur.next:
             if cur.next.val == val:
                 cur.next = cur.next.next
             else:
                 cur = cur.next
         return dummy.next