Reputation: 1
I tried to insert elements in head in a single linkedlist I don't understand what is wrong with my code. it says:
AttributeError: 'LinkedList' object has no attribute 'insert_head'
Here is my code:
class LinkedList:
def _init_(self):
# Empty LinkedList
self.head = None
# no of nodes in the LinkedList
self.n = 0
class Node:
def __init__(self,value):
self.data = value
self.next = None
def _len_(self):
return self.n
def insert_head(self,value):
#new node
new_Node = Node(value)
#Create onnection
new_Node.next = self.head
#Reasign head
self.head = new_Node
#Increment n
self.n = self.n + 1
L = LinkedList()
L.insert_head(1)
len(L)
Output should be 5
Upvotes: -1
Views: 80
Reputation: 16564
The reason is pretty obvious, LinkedList
has no insert_head
method. It's defined in Node
class.
In fact Node
objects should be a container for data and a reference to the next node, nothing more. They shouldn't be aware of the length of the linked-list for example.
You may refactor your code to something like this:
from __future__ import annotations
class Node:
def __init__(self, value):
self.data = value
self.next: Node | None = None
class LinkedList:
def __init__(self):
self.head: Node | None = None
self.n: int = 0
def __len__(self):
return self.n
def insert_head(self, value):
new_Node = Node(value)
new_Node.next = self.head
self.head = new_Node
self.n += 1
l = LinkedList()
l.insert_head(20)
print(len(l)) # 1
Upvotes: 0