This is a code to add a new node at the beginning of a linked list and then print the elements in the linked list. But when I run the program I get the following error in the last line when I call the ll1.print_LL() function:
AttributeError: 'NoneType' object has no attribute 'data'
And here is my code:
class Node:
def __init__(self, data):
self.data = data
self.ref = None
class LL:
def __init__(self):
self.head = None
def print_LL(self):
if self.head is None:
print("LL is empty")
else:
node = self.head
while self.head is not None:
print(node.data)
node = node.ref
def add_begin(self, data):
new_node = Node(data)
new_node.ref = self.head
self.head = new_node
ll1 = LL()
ll1.add_begin(10)
ll1.add_begin(20)
ll1.print_LL()
I have seen a post about a similar error on StackOverflow, but I'm still confused. Why am I getting this error in my code and how do I fix it?