Reputation: 75
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.
Upvotes: 1
Views: 101
Reputation: 2136
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
Upvotes: 1
Reputation: 61032
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
Upvotes: 1