class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add_to_front(self, data):
tempVar = Node(data)
tempVar.next = self.head
self.head = tempVar
def pop_from_front(self):
if self.head is None:
raise IndexError('Cannot pop empty list')
retval = self.head.data
self.head = self.head.next
return retval
def __str__(self):
datas = []
temp = self.head
while temp is not None:
datas.append(str(temp.data))
temp = temp.next
return ','.join(datas)
'''
This function returns a pointer to the Node at index `index`. It is used by
both __setitem__ and __getitem__
'''
def _get_node(self, index):
if index < 0:
raise IndexError(f'Cannot access index {index}.')
temp = self.head
for _ in range(index):
if temp is None:
raise IndexError(f'Cannot access index {index}.')
temp = temp.next
return temp
def __getitem__(self, index):
return self._get_node(index).data
def __setitem__(self, index, value):
self._get_node(index).data = value