1
    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.

zeyuxie
  • 65
  • 1
  • 7
  • Can you clarify your examples? I don't understand how you got your linked list or what do your parameters mean. – drum Nov 13 '16 at 22:57
  • add_after(ll, value, new_value), if ll = [2,1,8,2,2,4,2,5,2], calling add_after(ll, 2,-1) returns 2->-1->1->8->2->-1->2->-1->4->2->-1->5->2->-1->None. it adds new_value to each of the value. – zeyuxie Nov 13 '16 at 23:00
  • Possible duplicate of [Insert an element at specific index in a list and return updated list](http://stackoverflow.com/questions/14895599/insert-an-element-at-specific-index-in-a-list-and-return-updated-list) – Lord_PedantenStein Nov 13 '16 at 23:01
  • oh, sorry, I posted the wrong code, I just changed it. – zeyuxie Nov 13 '16 at 23:29

2 Answers2

1

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
quantummind
  • 2,086
  • 1
  • 14
  • 20
1

Below is a quick way to turn a list into a doubly linked list. Read through and understand it, then you should be able to modify it to suit your needs.

def link_list(l):
    if not l:
        return None
    head = TN(l[0])
    prev = head
    for val in l[1:]:
        curr = TN(val, prev)
        prev.right = curr
        prev=curr
    return head
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96