zeyuxie zeyuxie - 19 days ago 13
Python Question

linked list function that return a list

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

def add_after(ll,value,new):
item = ll
while item is not None:
if item.value == value:
newnode = LN(new, item.next)
item.next = newnode
break
else:
item = item.next


my add_after function takes a list such as [2,1,8,2,2,4,2,5,2], and a value and a new value. it add the new value to every value that appears in the list. for example:

l = [2,1,8,2,2,4,2,5,2],
calling add_after(a,2,-1) returns 2->-1->1->8->2->-1->2->-1->4->2->-1->5->2->-1->None. it add -1 after every 2 in the list

the problem with my add_after function is that it only add the new value to the first value that appears in the list.

for example, if I call add_after(ll,2,-1) to the list [1,8,2,4,2,5,2], it returns 1->8->2->-1->4->2->5->2->None

can someone help me to fix my add_after function so that it can apply to all of the value in the list? many thanks.

Answer

The break statement breaks the loop, so it will not got through the rest of the list.

There were other problems as well. A corrected version of the code:

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

    def add_after(self, value, new):
        item = self
        while item is not None:
            if item.value == value:
                newnode = TN(new, item.next)
                item.next = newnode
                item = newnode.next
            else:
                item = item.next
Comments