Python solution. Simple

  • 0

    First we remove all nodes that match val from the begining.
    Another way of doing this is to use a fake head, so the logic remains the same. I prefer my method because of the small space constants we gain by not using the fake head.
    After that, whenever we see a matching node in we point to and remove

    class Solution(object):
        def removeElements(self, head, val):
            :type head: ListNode
            :type val: int
            :rtype: ListNode
            if not head:
            while head is not None and head.val == val:
                q = head
                head =
            p = head
            while p is not None and is not None:
                if == val:
                    q =
                    p =
            return head

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.