Python solutions (O(n) extra space and in-place).


  • 0
    C
    # O(n) space
    def removeElements1(self, head, val):
        dummy = pre = ListNode(0)
        while head:
            if head.val != val:
                pre.next = ListNode(head.val)
                pre = pre.next
            head = head.next
        return dummy.next
     
    # in-place   
    def removeElements(self, head, val):
        dummy = pre = ListNode(0)
        dummy.next = head
        while head:
            if head.val == val:
                pre.next = head.next
            else:
                pre = pre.next
            head = head.next
        return dummy.next

  • 1
    C

    Another one which is easier than the above in-place solution:

    def removeElements(self, head, val):
        dummy = cur = ListNode(0)
        dummy.next = head
        while cur and cur.next:
            if cur.next.val == val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        return dummy.next

Log in to reply
 

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