Python solution


  • 0
    J

    Make a new head instead of old_head.
    Just for avoid to judge the head.

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def removeElements(self, head, val):
            """
            :type head: ListNode
            :type val: int
            :rtype: ListNode
            """
            dummy = ListNode(1)
            dummy.next = head
            cur = head
            pre = dummy
            while cur:
                if cur.val == val:
                    pre.next = cur.next
                else:
                    pre = pre.next
                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.