From LeetCode 203. Remove Linked List Elements

Description

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:

img

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

Example 2:

Input: head = [], val = 1
Output: []

Example 3:

Input: head = [7,7,7,7], val = 7
Output: []

Solutions

When we delete a node, we usually will let pointer point to the next node. But what if we want to delete the head node? We can move head node to the next.

def removeElements(self, head: ListNode, val: int) -> ListNode:
        dummy_head = ListNode(next=head) # add a dummy head
        cur = dummy_head
        while(cur.next!=None):
            if(cur.next.val == val):
                cur.next = cur.next.next #delete cur.next.next node
            else:
                cur = cur.next
        return dummy_head.next