简体   繁体   中英

What is wrong with my code to remove duplicates from Linked List?

New to Python and my code is passing all test cases other than input 1-->0, which it returns nothing instead of 1->0. does this have something to do with the value of None?

def RemoveDuplicates(head):
    if head == None or head.next == None:
        return 
    else:
        temp = head
        while(temp.next != None):
            if temp.data == temp.next.data:
                temp.next = temp.next.next
            else:
                temp = temp.next
        return head

Try is None instead of == None . Comparisons to singletons should be done using is or is not .

We can't see the class of head and what operations it has defined, is the __eq__ magic function defined on that class?

Is it possible that head.next == None evaluates to head.next.data == None for the class? In which case 0 == None evaluates to True.

As others have mentioned this is fixed by using head.next is None

I suspect you're supposed to return head in the first case regardless, but it doesn't seem like it should be triggering in this case unless the evaluations I mention above are happening.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM