Home > OS >  Attribute error in LinkedList implementation
Attribute error in LinkedList implementation

Time:10-07

I have tried to implement insert method in linked list but i get attribute error. "AttributeError: 'LinkedList' object has no attribute 'next'" Can anyone help? here is the code:

class Node():

 def __init__(self, value):
  self.value = value
  self.next = None

class LinkedList():

 def __init__(self):
  self.head = None
  self.tail = None

 def append(self, value):
  new_node = Node(value)
  if self.head == None:
   self.head = new_node
   self.tail = self.head
   self.length = 1
  else:
   self.tail.next = new_node
   self.tail = new_node 
   self.length  = 1

 def prepend(self,value):
  new_node = Node(value)
  if self.head == None:
   self.head = new_node
   self.tail = self.head
   self.length  = 1
  else:
   new_node.next = self.head 
   self.head = new_node
   self.length  = 1

 def insert(self, index, value): 
  new_node = Node(value)
  if index>=self.length:
   self.append(value)
   return
  elif index < 1:
   self.prepend(value)
   return
  else:
   header = self.traverseToIndex(index-1)
   pointer= self.traverseToIndex(index-1).next 
   header.next = new_node 
   new_node.next = pointer 
   self.length  = 1

 def traverseToIndex(self, index):
  counter = 0
  current_node = self.head
  while counter<=index:
   current_node = self.next 
   counter  = 1
  return current_node 
 
 def printl(self):
  temp = self.head
  while temp != None:
   print(temp.value , end = ' ')
   temp = temp.next
   print()
  print('Length = ' str(self.length)) 

l = LinkedList()
l.append(10)
l.append(5)
l.append(6)
l.prepend(1)
l.insert(3,99)

Insert method has the problem because of traverseToIndex() method. It tells me that current_node = current_node.next <-- doesn't have attribute "next" but since each object that was created has value and next, i do not understand why current_node doesn't have next attribute.

CodePudding user response:

Your self is a LinkedList instance, and has no next attribute. So change:

current_node = self.next 

to:

current_node = current_node.next 

Unrelated, but:

  • the while condition should be counter < index instead of counter <= index
  • it is a waste of time to call traverseToIndex twice. Drop that second call, and instead do pointer = header.next
  • Use 4-spaced indents instead of 1 space. It is hard to spot you have an indentation error in the printl method, where print() is probably not supposed to be part of the loop.
  • Related