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
The reason is pretty obvious,
LinkedListhas noinsert_headmethod. It's defined inNodeclass.In fact
Nodeobjects 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: