Accepted Python solution with 1 dummy head and 3 pointers


  • 0
    X

    I used a dummy head node linked before the head node and 3 pointers to keep track of the previous node, the temporary node, and the current node. The temporary node is the node that is waiting for further steps to check if it has duplications. Below is my code. Any improvement?

    class Solution:
        # @param head, a ListNode
        # @return a ListNode
        def deleteDuplicates(self, head):
            if head == None:
                return None
            dummyhead = ListNode(-1)
            prev = dummyhead
            temp = head
            cur = head.next
            value = head.val
            while cur != None:
                if cur.val == value:
                    cur = cur.next
                    temp = None
                elif temp != None:
                    prev.next = temp
                    prev = temp
                    temp = cur
                    value = cur.val
                    cur = cur.next
                else:
                    temp = cur
                    value = cur.val
                    cur = cur.next
            prev.next = temp
            return dummyhead.next

Log in to reply
 

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