python - Function that iterates through a linked list -
class ln: def __init__(self,value,next=none): self.value = value self.next = next def list_to_ll(l): if l == []: return none front = rear = ln(l[0]) v in l[1:]: rear.next = ln(v) rear = rear.next return front def add_after(ll,value,new): item in ll: if item == value: ll.insert(ll.index(value),new)
i working on iterative function named add_after
. takes linked list , 2 values, value , new. mutates linked list such every occurrence of value followed new. example:
a = list_to_ll([2,1,8,2,2,4,2,5,2])
add_after(a,2,-1) results in referring linked list containing values 1->8->2->-1->4->2->-1->5->2->-1->none.
add_after(a,2,2) original list in results in referring linked list containing values 1->8->2->2->4->2->2->5->2->2->none.
plus( not allowed use lists, tuples, sets, or dicts in code)
use linked lists processing only
when run add_after
gives me error:
add_after(ll,2,-1) item in ll: typeerror: 'ln' object not iterable
can me fix add_after
function? many thanks.
- make
ln
iterable, defining__iter__
methods yields nodes: - make
add_after
link new node.
class ln: def __init__(self, value, next=none): self.value = value self.next = next def __iter__(self): # yield linked node (including first node) node = self while node not none: yield node node = node.next def list_to_ll(l): if l == []: return none front = rear = ln(l[0]) v in l[1:]: rear.next = ln(v) rear = rear.next return front def add_after(ll, value, new): item in ll: if item.value == value: ll.next = ln(new, ll.next) # make new node , link after current node break # todo: handle not-found case. ll = list_to_ll([2,1,8,2,2,4,2,5,2]) add_after(ll, 2, -1) item in ll: print(item.value) # prints 2, -1, 1, 8, 2, 2, 4, 2, 5, 2
update after reading op's comment => changing add_after
(manually loop through nodes):
def add_after(ll, value, new): node = ll while node not none: if node.value == value: node.next = ln(new, node.next) break node = node.next
note: made add_after
add 1 node. leave work add multiple nodes.
Comments
Post a Comment