Simple & clear python solution

  • 7

    First we remove all (if any) target nodes from the beginning (we do it because the removing logic is slightly different from when the node is not in the head). After that we just loop over all nodes, if the next one is one that should be removed, just get it out of the list by moving the next pointer to the next-next node. Otherwise just move along the list.

    class Solution(object):
        def removeElements(self, head, val):
            while head is not None and head.val == val:
                head =
            current = head
            while current is not None:
                if is not None and == val:
                    current =
            return head

Log in to reply

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