Reputation: 1
class Node:
def __init__(self, data = None, next = None):
self.data = data
self.next = next
class link:
def __init__(self):
self.head = None
def insert_begining(self, data):
node = Node(data, self.head)
self.head = node
def print(self):
itr = self.head
space = ''
while itr:
space += str(itr.next) + '-->'
itr = itr.next
print(space)
if __name__ == '__main__':
root = link()
root.insert_begining(5)
root.insert_begining(10)
root.print()
#output of my code = <__main__.Node object at 0x00000209175AB9A0>-->None-->
Upvotes: 0
Views: 522
Reputation: 54168
Your Node
class need a __str__
method to tell how to print it
class Node:
def __str__(self):
return str(self.data)
Then in Link
, you may use itr
and not itr.next
in the result construction, and I suggest a list to join instead of concatenation to avoid an arrow pointing to nothing at the end
def print(self):
itr = self.head
result = []
while itr:
result.append(str(itr))
itr = itr.next
print(' --> '.join(result))
root = link()
root.insert_begining(5)
root.insert_begining(10)
root.insert_begining(15)
root.print() # 15 --> 10 --> 5
Upvotes: 1
Reputation: 126
You should add the str
method to Node class
def __str__(self):
return 'The string that represent the node'
If data is a string then it could be:
def __str__(self):
return self.data
Upvotes: 0