Reputation: 151
I would like to first create my linkedlist and then print the list list nodes. I tried a few methods but always getting a wrong output.
Below is my code:
class node:
def __init__(self, dataVal=None):
self.dataVal = dataVal
self.nextVal = None
class LinkedList:
def __init__(self):
self.headVal = None
def printList(self):
printVal = self.headVal
while printVal is not None:
print(printVal.dataVal)
printVal = printVal.nextVal
def insertEnd(self, n_node):
new_node = node(n_node)
if self.headVal is None:
self.headVal = node(new_node)
else:
end = self.headVal
while(end.nextVal):
end = end.nextVal
end.nextVal = new_node
def createList(array, n):
linkedList = LinkedList()
for i in range(n):
linkedList.insertEnd(array[i])
return linkedList
if __name__=='__main__':
t = 2
n = [5,6]
array = [[1,2,3,4,5], [2,3,6,7,5,1]]
for i in range(t):
head = createList(array[i], n[i])
print(head.printList())
My current output:
<__main__.node object at 0x0000026152300400>
2
3
4
5
None
<__main__.node object at 0x00000261523257B8>
3
6
7
5
1
None
My expected should be:
<__main__.node object at 0x0000026152300400>
1
2
3
4
5
<__main__.node object at 0x00000261523257B8>
2
3
6
7
5
1
I do not know why the "None" appears and also why the object printed as well. Can anyone help?
Upvotes: 1
Views: 70
Reputation: 46710
Remove the print to get rid of None
. Change
print(head.printList())
to
head.printList()
Also
if self.headVal is None:
is equivalent to but more pythonic
if not self.headVal:
Upvotes: 1