Implementing an insertion, delete, find, and reverse method for singly linked list in python

I need to write a python program that: Insert: this method takes a value as a parameter, and adds a node which contains the value to the end of the linked list

● Insert: this method takes a value as a parameter, and adds a node which contains the value to the end of the linked list

● Delete: this method deletes a node from the linked list. If an index is passed as a parameter, then the method should delete the node at this index. If no index is passed, then delete the first item in the list

● Find: this method takes a value as a parameter, and returns the index of the first node which contains this value. If no nodes are found to contain this value, return False

● Reverse: this method reverses the Linked List

To do so I have this so far:

  def __init__(self, dataval=None):
    self.dataval = dataval
    self.nextval = None

class LinkedList:
  def __init__(self):
    self.headval = None
  def __str__(self):
    node = self.headval
    output = "[ "
    while(node != None):
      output = output + str(node.dataval) + ", "
      node = node.nextval
    if(len(output) > 2):
      output = output[:-2]
    return output + " ]"


def insert(self, val):
  new_node= Node(val)
  if self.headval is None:
    self.headval=new_node
    return
  n=self.headval
  while n.ref is not None:
    n=n.ref
  n.ref=new_node;


def delete(self, index=0):
  if self.headval is None:
    print("This list has no element to delete")
    return 
        
  if self.headval ==index:
    self.headval=self.headval.ref 
    return 
        
  n=self.headval 
  while n.ref is not None:
    if n.ref.item==x:
      break
    n=n.ref

  if n.ref is None:
    print("Item not found in list")
  else:
    n.ref=n.ref.ref


def find(self, val):
  current=self.headval 
  count=0
  while(current):
    if (count==val):
      return current
    count+=1
    current=current.next
  assert(False)
  return 0 

        
def reverse(self):
  prev=None
  n=self.headval
  while n is not None:
    next=n.ref
    n.ref=prev
    prev=n
    n=next
  self.headval=prev

# Tests
# Insertion
a = LinkedList()
a.insert(1)
a.insert(2)
a.insert('a')
a.insert(3)
print(str(a) == "[ 1, 2, a, 3 ]")

# Deletion
a.delete()
print(str(a) == "[ 2, a, 3 ]")
a.delete(2)
print(str(a) == "[ 2, a ]")

# Find
a.insert('b')
a.insert('c')
a.insert('b')
print(a.find('b') == 2)
print(a.find('c') == 3)
print(a.find('d') == False)

# Reverse
a.reverse()
print(str(a) == "[ b, c, b, a, 2 ]")

When I try to run it, it says "AttributeError: 'LinkedList' object has no attribute 'insert'". Why so?

1 answer

  • answered 2020-10-29 22:15 Montmorency

    Is the indentation correct? It looks like your insert method isn't nested inside the linked list class.