Coding a Linked List#
Here is code you should copy-paste in a file called linkedlist.py:
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):
pass
def pop_from_front(self):
pass
def __str__(self):
pass
def __getitem__(self, index):
pass
def __setitem__(self, index, value):
pass
Notice the functions of the LinkedList class are unimplemented. Here is what should happen in each function.
add_to_front(self,data)should add a new Node containingdatato the front of the linked list. Your linked list will be one Node longer after calling this function. This function must be \(O(1)\).pop_from_front(self)should remove the first Node of the linked list, and return the value of its data. For example, if the linked list contains a Node containing 6, and then a Node containing 5, the function should return 6, and alter the linked list to now only containing a Node with 5. If the linked list is empty, this function should raise anIndexError. This function must be \(O(1)\).__str__(self)is the function that is called whenever you try to cast a linked list object to a string, such as withstr(my_ll)orprint(my_ll). This function should return a string with the comma-separated contents of the linked list. For example, a linked list with a Node containing 6, and then a Node containing 5 would return the string"6,5". This function must be \(O(n)\).__getitem__(self, index)is how we overload the square brackets for access. For example,print(my_ll[3])is equivalent toprint(my_ll.__getitem__(3)). This function should return the contents of theindexth node in the linked list. Ifindexis an illegal index (too big or too small), the function should raise anIndexError. This function must be \(O(n)\).__setitem__(self, index, value)is how we overload the square brackets for assignment. For example,my_ll[3]=6is equivalent tomy_ll.__setitem__(3, 6). Ifindexis an illegal index, the function should raise anIndexError. This function must be \(O(n)\).
Upload your solution to the submit site as project linkedlist1. There are
test cases to help you check your work.