diff --git a/04_linkedList/ll.py b/04_linkedList/ll.py index e1b26c9..6e1b751 100644 --- a/04_linkedList/ll.py +++ b/04_linkedList/ll.py @@ -12,7 +12,7 @@ class SingleListItem(): """ def __init__(self, value, nexti=None): self.value = value - self.nexti = nexti + self.nexti = nexti # pointer of the next element in the list def has_next(self): """ @@ -25,10 +25,49 @@ class SingleLinkedList(): Linked list with only one link between items. The list can only be traversed one way""" - def __init__(): - self.root= SinglelistItem(None, None) # The head + def __init__(self): + self._size = 0 + self._root = None # reference of the head + + def add(self, value): + """ + Adds a new element to the end of the list + """ + if self._root is None: + # empty tree + self._root = SingleListItem(value) + else: + curr = self._root + while(curr.nexti is not None): + #gets last item + curr = curr.nexti + + item = SingleListItem(value) + curr.nexti = item + + self._size += 1 + + def __len__(self): + # Returns the number of elements in the list + return self._size + + def __str__(self): + """ + Prints out all values in the list + """ + to_print = "" + curr = self._root + to_print += str(curr.value) + while(curr.nexti is not None): + curr = curr.nexti + to_print += ", " + str(curr.value) + + return to_print if __name__ == "__main__": - a = 12 - t = SingleListItem(12) - print t.has_next() + ll = SingleLinkedList() + ll.add(3) + ll.add(4) + ll.add(5) + ll.add(6) + print ll