Python Recursive Solution with comments, 56ms


  • 0
    H
    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def deleteDuplicates(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """ 
            # zero or only one node
            if head == None or head.next == None:
                return head
            
            # if not unique
            if head.val == head.next.val:
                # discard the second nodes with the same value
                while head.next and head.val == head.next.val:
                    head.next = head.next.next
                # also discard the first node
                return self.deleteDuplicates(head.next)
            # if unique
            else:
                # keep the head node
                head.next = self.deleteDuplicates(head.next)
                return head
    

Log in to reply
 

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