A easy to understand python solution


  • 4
    C
    def deleteDuplicates(self, head):
        # Add a dummy node point to the current list
        newhead = ListNode(0)
        newhead.next = head
        val_need_to_be_deleted = None
        tail = newhead
        
        while head:
            
            # Triger delete mode if current has the same val as the next
            if head and head.next and head.val == head.next.val:
                val_need_to_be_deleted = head.val
            
            # Not a dup if delete mode is off or the current value doesn't match the value need to be deleted
            if val_need_to_be_deleted == None or head.val != val_need_to_be_deleted:
                # add it to the newlist
                tail.next = head
                tail = head
                
            head = head.next
            
        tail.next = None
        return newhead.next

  • 0

    @ccacca
    what does tail.next = None means?


  • 0
    W

    @Zura You need this because otherwise the list will continue. Try removing the line and submit the rest code, you will see what I mean


  • 0
    S

    @ccacca said in A easy to understand python solution:

    if val_need_to_be_deleted == None or head.val != val_need_to_be_deleted:

    Perfect and clean! Love this solution. However, one suggestion. In the code quoted above, val_need_to_be_deleted == None is not necessary. If it is None, then its going to fail the next condition anyway!


Log in to reply
 

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