I want my code to print numbers from 0 to 5, instead it prints only 0 as output. Can anyone correct the code.
code:
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def display(self):
ptr = self.head
while ptr is not None:
print(ptr.value)
ptr = ptr.next
l1 = LinkedList()
ptr = l1
ptr.head = Node(0)
ptr.head.next = None
a = [1, 2, 3, 4, 5]
for i in a:
dummy = Node(i)
ptr.next = dummy
ptr = ptr.next
# Displaying the linked list
l1.display()
I tried to build a simple linked list in python and was trying to print the numbers that were stored in the linked list, but there is something wrong with my code and it isn’t working as I wanted it to be.
>Solution :
The issue is because when you initialized ptr, and set ptr.head.next = None, you didn’t move the ptr forward.
Try:
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def display(self):
ptr = self.head
while ptr is not None:
print(ptr.value)
ptr = ptr.next
l1 = LinkedList()
ptr = l1
ptr.head = Node(0)
ptr.head.next = None
ptr = ptr.head
a = [1, 2, 3, 4, 5]
for i in a:
dummy = Node(i)
ptr.next = dummy
ptr = ptr.next
# Displaying the linked list
l1.display()
Running it produces:
0
1
2
3
4
5