dev-sps
dev-sps

Reputation: 23

print_linked_list method printing None after the last value in linked list

Why my print_list_method is printing None at the end of the output?
I am also checking, if the current_node is None in the while loop of my print_linked_list method. I would really appreciate if someone help me in finding or explaining the issue here.

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None


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

    def append(self, value):
        if self.head is None:
            self.head = Node(value)
            return

        node = self.head
        while node.next:
            node = node.next

        node.next = Node(value)

    def print_linked_list(self):
        current_node = self.head
        while current_node:
            print(current_node.value)
            current_node = current_node.next

    def prepend(self, value):
        if self.head is None:
            self.head = Node(value)
            return
        new_node = self.head
        self.head = Node(value)
        self.head.next = new_node
        return

l = LinkedList()
l.append(1)
l.append(2)
l.append(3)
l.prepend(5)
print(l.print_linked_list())

Output: Output of the code

Upvotes: 2

Views: 464

Answers (1)

Shubham Sharma
Shubham Sharma

Reputation: 71689

Your print_linked_list() method prints the required linked list and returns None so there is no need to call this method inside print statement so instead of calling print(l.print_linked_list()) just call l.print_linked_list() and you will get the desired result.

Upvotes: 3

Related Questions