Share my python solution, using two pointers


  • 0
    R
    class Solution:
        # @param {ListNode} head
        # @return {ListNode}
        def deleteDuplicates(self, head):
            if head is None:
                return None
            if head.next is None:
                return head
    
            p1, p2 = head, head.next
            flag = False
            while p2 is not None:
                if p1.val == p2.val:
                    p1, p2 = self.utilRemoveDuplicates(p1, p2)
                else:
                    p1 = p2
                    p2 = p2.next
    
            return head
    
        def utilRemoveDuplicates(self, p1, p2):
            while hasattr(p1, "val") and hasattr(p2, "val") and (p1.val == p2.val) and (p2 is not None):
                p2 = p2.next
    
            if p2 is None:
                p1.next = None
            else:
                p1.next = p2
                p1 = p2
                p2 = p2.next
    
            return p1, p2

Log in to reply
 

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