Nov-21-2020, 08:22 PM
Let's go back to the basic design.
ListNode is presumably a node within your list. It has properties of a value and a link to the next node (linked list). This is not the whole list.
Your listprint routine, by its name, is to print the whole list. You should NOT have that as a method of an individual node. Rather, if you want to print the value of an individual node, call the method nodeprint() and just print the value.
You could then create a function at the top level that runs the list and calls nodeprint() on each linked node.
Also, when you create a new node, you should update the next of the prior linked node at that time. Using next.next is going to get you into trouble.
Look at the below. There are still issues in how I create the linked list in that it is not generalizable.
ListNode is presumably a node within your list. It has properties of a value and a link to the next node (linked list). This is not the whole list.
Your listprint routine, by its name, is to print the whole list. You should NOT have that as a method of an individual node. Rather, if you want to print the value of an individual node, call the method nodeprint() and just print the value.
You could then create a function at the top level that runs the list and calls nodeprint() on each linked node.
Also, when you create a new node, you should update the next of the prior linked node at that time. Using next.next is going to get you into trouble.
Look at the below. There are still issues in how I create the linked list in that it is not generalizable.
linkedlist = [] class listnode: def __init__(self,nvalue=0,nextnode=None,priornode=None): self.val = nvalue self.next = nextnode self.prior = priornode def printlist(thelist): node = thelist[0] while node.next != None : print(node.val) node = thelist[node.next] #build a list node1 = listnode(2) linkedlist.append(node1) node1 = listnode(5,None,0) linkedlist[0].next = 1 linkedlist.append(node1) node1 = listnode(4,None,1) linkedlist[1].next = 2 linkedlist.append(nodel1)