Python solution. Simple


  • 0
    P

    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 p.next we point to p.next.next and remove p.next.

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

Log in to reply
 

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