Search code examples
pythonpython-3.xlinked-listsingly-linked-list

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.

Does anyone have a possible solution?


Solution

  • You were passing a LinkedNode() object as an argument to .append() function:

    class LinkedNode:
        def __init__(self, value, nxt=None):
            self.val = value
            self.nxt = nxt
    
    class LinkedList:
        def __init__(self, head=None):
            self.head = head
    
        def append(self, new_val):
            node = LinkedNode(new_val, None) #Creation of LinkedNode from integer
            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(2) #Argument must be integer, not LinkedNode(integer)
    l1.append(3) #Because you are already converting integer to LinkedNode on append function
    l1.append(4)
    l1.print()
    

    Output:

    2
    3
    4