Accepted python code for deleting all duplicates in a linked list


  • 0
    L

    My submission are listed bellow. Basically the code use three pointer to scan through the linked-list namely back, middle, and head. middle and head is used to determine whether duplicates exist. If so delete them. To address the case when the first several elements are duplicates. I added an element in front of the whole list. Any comments on improving it would be appreciated!

    class Solution:
        # @param head, a ListNode
        # @return a ListNode
        def deleteDuplicates(self, head):
            if (not head) or (not head.next):
                return head
            else:
                headnew= ListNode(1) # add a head node
                headnew.next=head
                front=head.next
                middle = head
                back=headnew
                flag = 0
                while front:
                    if front.val == middle.val:
                        front=front.next
                        flag +=1
                    else:
                        if flag == 0:
                            back=back.next
                            middle=middle.next
                            front = front.next
                        else:
                            back.next=front
                            middle = front
                            front = front.next
                            flag=0
                if flag>0:
                    back.next=None
                return headnew.next

Log in to reply
 

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