This is my code for the implementation of a singly linked list in Python:
class SList:
def __init__(self):
self.root = None
self.size = 0
def insert(self, item):
try:
if not item:
raise ValueError
self.size += 1
if self.root is None:
self.root = Node(item)
else:
p = Node(item)
p.next = self.root
self.root = p
except ValueError:
raise ValueError('Cannot add None item to a list')
def remove(self, index):
try:
if index < 0 or index >= self.size:
raise ValueError
current = self.root
count = 0
while count < index:
current = current.next
count += 1
current.next = current.next.next
self.size -= 1
except ValueError:
raise ValueError('Index cannot be negative or greater than the size of the list')
def __sizeof__(self):
return self.size
class Node:
def __init__(self, data):
try:
if not data:
raise ValueError
self.data = data
self.next = None
except ValueError:
raise ValueError('Node cannot be instantiated without an item')