203. Remove linked list elements

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

Example 1:

Input: head = [1,2,6,3,4,5,6], val = 6 Output: [1,2,3,4,5]

  • code
class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        if not head:
            return None

        while head and head.val == val:
            head = head.next

        if head and head.next:
            pre, cur = head, head.next
            while cur:
                if cur.val == val:
                    pre.next = cur.next
                    cur = cur.next
                else:
                    pre, cur = pre.next, cur.next
        return head
  • code
class Solution:
    def removeElements(self, head, val):

        dummy_head = ListNode(-1)
        dummy_head.next = head
        
        current_node = dummy_head
        while current_node.next:
            if current_node.next.val == val:
                current_node.next = current_node.next.next
            else:
                current_node = current_node.next
                
        return dummy_head.next