I have just started learning about linked lists and I can't seem to add a new node using a function. Here is my code:
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return self.data
class LinkedList:
def __init__(self, nodes=None):
self.head = None
if nodes is not None:
node = Node(data=nodes.pop(0))
self.head = node
# print(self.head)
for elem in nodes:
# print(elem)
node.next = Node(data=elem)
node = node.next
# print(node)
def __repr__(self):
node = self.head
nodes = []
while node is not None:
nodes.append(node.data)
node = node.next
nodes.append("None")
return " - > ".join(nodes)
def __iter__(self):
node = self.head
while node is not None:
yield node
node = node.next
def add_first(self, node):
node.next = self.head
self.head = node
llist = LinkedList(["c"])
llist.add_first("j")
print(llist)
When I run this, I get AttributeError: 'str' object has no attribute 'next'. Why does it not recognise the 'next' from the Node class?
node = Node(node)at the start of youradd_firstfunction.