I have the following class based linked list created in Python. I need some help in the best way to actually call and test this (print the results and output to the screen).
For an accepted answer, could someone please 1. use my existing code, to test/output results showing the linked list implementation 2. Make any comments on my existing code and suggestions as to how it could be improved (if any)
I am not sure how to "call" the testing method to see the results, or whether it is better to take that out and test outside the class. If the latter is preferred, could someone please demonstrate this, as I am unclear/unsure of the creation of nodes and next pointer objects in order to test the class.
class Node: def __init__(self,contents=None, next=None): #Here we are defining the two attributes - contents of the list and the next pointer self.contents = contents self.next = next def getContents(self): return self.contents def __str__(self): return str(self.contents) def print_list(node): while node: print(node.getContents()) node=node.next print() def testing(): #Add content to each node node1=Node("A") node2=Node("C") node3=Node("D") node4=Node("B") #Define the pointers for each node (e.g. follow through A to B to C to D) node1.next=node4 node4.next=node2 node2.next=node3 print(print_list(node1))
I am also unclear on the implementation, as when creating a queue you would have something like the below to add an element. Would this not be needed here for a linked list?
Method for adding an item to a queue
def add(self,item): #method to add something self.items.append(item) #to add something, use append
This would be added to the queue (and tested) like so:
myQ.add("A") myQ.add("B") myQ.add("C")
I think some guidance on what exactly is happening (comments) would be helpful too.