careercup/CtCI-6th-Edition-Python

C02_P01 Tail removed

fg91 opened this issue · 1 comments

fg91 commented

Hey,

I found the following Problem with the solution of 2.1.
If we create a duplicate at the end of the linked list, the tail is removed and the add method does not work anymore.

l1 = LinkedList()
l1.add_multiple([1,2,3,2])
l1 = removeDups(l1)
l1.__str__()
l1.add(4)
l1.__str__()

When trying those lines, you will find, that the 4 is not added the Linked List.

I suggest the following changes:

def removeDups(ll):
    if ll.head is None:
        return
    
    current = ll.head
    found = set([current.value])
    while current.next:
        if current.next.value in found:
            if current.next is ll.tail:
                ll.tail = current
            else:
                current.next = current.next.next
        else:
            found.add(current.next.value)
            current = current.next
    
    return ll

and

def removeDups_FollowUp(ll):
    if ll.head is None:
        return
    
    current = ll.head
    while current:
        runner = current
        while runner.next:
            if runner.next.value == current.value:
                if runner.next is ll.tail:
                    ll.tail = runner
                else:
                    runner.next = runner.next.next
            else:
                runner = runner.next
        current = current.next
    
    return ll

What do you think?

Best regards

F

Thanks for pointing this out! I've fixed the issue and added a test for this.