Skip to main content

Remove Linked List Elements

Question

Given a singly linked list and a value, delete all nodes containing this value, and return the head of the modified list.

Example 1
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

Solution

all//Remove Linked List Elements.py


# 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:
if head is None:
return None

# create a dummy node to make sure head is not None
dummyHead = ListNode(0)
dummyHead.next = head
p = dummyHead

while p and p.next:
if p.next.val == val:
# remove the node
p.next = p.next.next
else:
# move to next node
p = p.next

return dummyHead.next