Aditya Parihar
Aditya Parihar

Reputation: 1

my code for linked list is printing address in python

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

Answers (2)

azro
azro

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

Mussi
Mussi

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

Related Questions