Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python linked-list issues of receiving memory addresses when printing unless double calling

I am creating a Linked List implementation and I cannot fix this error of having to double call node.val.val to print the data instead of the memory address.

Here is my implementation:

class LinkedNode:
    def __init__(self, val, nxt=None):
        self.val = val
        self.nxt = nxt

class LinkedList:
    def __init__(self, head=None):
        self.head = head

    def append(self, new_val):
        node = LinkedNode(new_val, None)
        if self.head:
            curr = self.head
            while curr.nxt:
                curr = curr.nxt
            curr.nxt = node
        else:
            self.head = node

    def print(self):
        curr = self.head
        while curr:
            **print(curr.val)**
            curr = curr.nxt


l1 = LinkedList()
l1.append(LinkedNode(2))
l1.append(LinkedNode(3))
l1.append(LinkedNode(4))
l1.print()

When the line in the print function is "print(curr.val)", the function prints memory addresses. When the line is "print(curr.val.val)", the function prints 2,3,4.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Does anyone have a possible solution?

>Solution :

Because in these lines you are creating LinkedNode objects not values!

l1.append(LinkedNode(2))
l1.append(LinkedNode(3))
l1.append(LinkedNode(4))

After that, you created a new LinkedNode("LinkedNode", None) within the scope of the append function.

Change it to:

l1.append(2)
l1.append(3)
l1.append(4)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading