Mrfuzzy Mrfuzzy - 5 months ago 9x
Python Question

Trying to implement a function that removes all occurrences of a value from a linked list in python

class LN:
def __init__(self,value,next=None):
self.value = value = next

def remove(ll,v):
head = ll
if head.value == v:
head =

while != None:
if == v: =
ll =
return head

For some reason this function removes only some of the values v but not all of them, how can I modify it so that it removes all occurrences of v?

Thank you !


There's couple of issues with the existing code. When processing the beginning of the list you have to handle the case where there are more than one item at the beginning of the list that needs to be removed. So instead of if you need a loop and once you're done with it you can return if all items have been removed

while ll and ll.value == v:
    ll =

# Return if list is depleted or was empty to begin with
if not ll:
    return ll

At this point you've either returned or ll points to the first node that should be kept, the head of the new list. Since we need to return the head we have to store it and then process all the following nodes. That can be done by checking the value of next node. If it's v then it can be skipped over:

# At this point ll points to head of the new list
head = ll
    if == v: =
        ll =

return head