203. Remove Linked List Elements
[Easy] “Remove all elements from a linked list of integers that have value ‘val’."
Python3:
# 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:
# skip any initial of val
while head and head.val == val:
head = head.next
if not head:
return head
# run through rest of linked list
next_node = head
while next_node and next_node.next:
if next_node.next.val == val:
# remove element
next_node.next = next_node.next.next
else:
next_node = next_node.next
return head