Problem
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.
Algorithm
First determine if the first number is the remove value, if it is then move the head pointer directly. Then determine if the following number are the remove value, if they are move the front pointer.
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]:
while head and head.val == val:
head = head.next
if not head:
return None
ps, pt = head, head.next
while pt:
while pt and pt.val == val:
ps.next = pt.next
pt = pt.next
if not pt:
return head
ps = ps.next
pt = pt.next
return head