Intuition

  • Utilize the dummy variable to make sure to delete one after another at a time.
  • Only update previous to the next node if it does not already point to the next node (since you skipped the previous node you were supposed to move to before you updated cur.next)

Code

# 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: Optional[ListNode], val: int) -> Optional[ListNode]:
        root = ListNode(-1)
        root.next = head
        prev = root
        cur = root.next
        while cur:
            if cur.val == val:
                prev.next = cur.next
            else:
                prev = prev.next
            cur = cur.next
        return root.next

Notes


References

https://leetcode.com/problems/remove-linked-list-elements/description/