Linked list implementation in python issue

Question:

I have been trying to implement a linked-list in python.Any call of a variable inside a function in Python is by default call by reference.I have this code:

For the list_node:

class list_node:

    def __init__(self,obj,next_listnode):
        self.obj = obj
        self.next_listnode  = next_listnode

For the linked_list:

class linked_list:
    
    def __init__(self,list_node):
        self.list_node =list_node

    def add_node(self,obj):
        current = self.list_node
        while(current.next_listnode is not None):
            current = current.next_listnode
        current.next_listnode = obj;

    def print_linkedlist(self):
        current  = self.list_node
        while(current.next_listnode is not None):
            print("",current.obj)
            print("n")
            current = current.next_listnode

I I create 2 list_nodes 1 of which I add it as the initial list_node of the linked list and the other using the function add_node:

A = list_node("John",None)
B = list_node("Mike",None)
liste = linked_list(A)
liste.add_node(B)

liste.print_linkedlist();

However when I call the print_linkedlist function it only prints A list_node

What am I doing wrong?
However

I tried not calling the add_node function but it didnt print anything.

Asked By: Volpina

||

Answers:

If you add one more node to your list, the problem becomes a bit more clear:

A = list_node("John",None)
B = list_node("Mike",None)
C = list_node("Biff",None)
liste = linked_list(A)
liste.add_node(B)
liste.add_node(C)

liste.print_linkedlist()

This prints "John" and "Mike" — so the problem isn’t that you’re only printing the first node, it’s that you’re not printing the last node.

That’s because your print_linkedlist function stops iterating when current.next_listnode is not None — i.e. it will stop as soon as it reaches the last node (the one with no "next" node), and it won’t print that node.

I’d suggest doing this instead:

    def print_linkedlist(self):
        current = self.list_node
        while current:
            print(current.obj)
            current = current.next_listnode

in order to print all nodes of the list.

Answered By: Samwise