Skip to main content

Remove Linked List Elements


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


all//Remove Linked List

# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val = 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) = head
p = dummyHead

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