Friedrich Ewald My Personal Website

Leetcode: Remove element from list

Given the head of a linked list, remove all items with val. Afterwards, return the new head. To solve this problem, we need to consider three cases. The element can be in the beginning, in the middle or at the end. For the middle case, we can just define = This also works for the end, except that we need to make sure that the next element is not None. The beginning is a little bit more difficult. Here we can work around this problem by adding a pseudo-node in front of the beginning and then always look at the next one. At the end we return The other corner case is if two nodes that need to be deleted are right next to each other. In this case we cannot move the pointer forward.

from typing import Optional

# Definition for singly-linked list.
class ListNode:
  def __init__(self, val=0, next=None):
    self.val = val = next
  def __repr__(self) -> str:
    l = str(self.val)
    if is not None:
      l += f", {}"
    return l

class Solution:
  def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
    new_head = ListNode(0, head)
    n = new_head
    while n is not None:
      if is not None and == val: =
        n =


if __name__ == '__main__':
  s = Solution().removeElements
  l = ListNode(1, ListNode(2, ListNode(6, ListNode(3, ListNode(4, ListNode(5, ListNode(6)))))))
  print(s(l, 6))
Runtime: 169 ms, faster than 5.14% of Python3 online submissions for Remove Linked List Elements. Memory Usage: 17.8 MB, less than 81.69% of Python3 online submissions for Remove Linked List Elements.

About the author

is an experienced Software Engineer with a Master's degree in Computer Science. He started this website in late 2015, mostly as a digital business card. He is interested in Go, Python, Ruby, SQL- and NoSQL-databases, machine learning and AI and is experienced in building scalable, distributed systems and micro-services at multiple larger and smaller companies.