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 :
- The linked list is empty, i.e. the head node is None.
- Multiple nodes with the target value in a row.
- The head node has the target value.
- The head node, and any number of nodes immediately after it have the target value.
- All of the nodes have the target value.
- 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