Python Doubly Linked List - Inserts data into a new node after the given node -
i writing code doubly linked list in python. however, struggling how insert data new node after given node. , understanding wrong constructing doubly linked list's insertafter() method in python. want know how fix code.
this code far:
class node: # constructor initialize data # if data not given user,its taken none def __init__(self, data=none, next=none, prev=none): self.data = data self.next = next self.prev = prev class doubly_linked_list: def __init__(self): self.head = none self.tail = none # inserts data new node after given node def insertafter(self, node, data): runner = node(none, data, node, none) runner.next = self.head if self.head not none: self.head.prev = runner self.head = runner # # adds given value last value in list def addlast(self, data): if self.head not none: runner = self.head while(runner.next != none): runner = runner.next runner.next = node(data, none, runner) self.tail = runner.next else: self.head = node(data) self.tail = self.head def print_next_list(self): # traverse forwards runner = self.head while (runner not none): print(runner.data) runner = runner.next def print_prev_list(self): # traverse backwards runner = self.tail while (runner not none): print(runner.data) runner = runner.prev # initializing list alist = doubly_linked_list() alist.addlast(3) alist.addlast(5) alist.addlast(7) alist.addlast(9) alist.addlast(11) alist.print_next_list() print() alist.print_prev_list() alist.insertafter(5,7) #this shows me error.
i have no idea doing in:
def insertafter(self, node, data): runner = node(none, data, node, none) runner.next = self.head if self.head not none: self.head.prev = runner self.head = runner
this should be:
def insertafter(self, node, data): newnode = node(data, node.next, node) node.next = newnode
here create new node data passed , place after passed node.
Comments
Post a Comment