diff --git a/04_linkedList/ll.py b/04_linkedList/ll.py index 6e1b751..4a03da2 100644 --- a/04_linkedList/ll.py +++ b/04_linkedList/ll.py @@ -9,7 +9,7 @@ class SingleListItem(): """ Item from a Single Linked List. Contains only a previous next element, and a value - """ + """ def __init__(self, value, nexti=None): self.value = value self.nexti = nexti # pointer of the next element in the list @@ -19,12 +19,12 @@ class SingleListItem(): Returns True if the item has a next value """ return not (self.nexti is None) - + class SingleLinkedList(): """ Linked list with only one link between items. The list can only be traversed one way""" - + def __init__(self): self._size = 0 self._root = None # reference of the head @@ -44,20 +44,37 @@ class SingleLinkedList(): item = SingleListItem(value) curr.nexti = item - + self._size += 1 - + + def delete_item(self, node=None): + """ + Deletes the nth node of the list. (0 being the first element) + If node is None, deletes the first element of the list. + """ + if node == None: + item = self._root.nexti + self._root = item + self._size -= 1 + elif node >= self.size(): + raise Exception("Requested value out of list bounds") + + + + def __len__(self): # Returns the number of elements in the list return self._size - + def __str__(self): """ Prints out all values in the list + This way of doing is not exactly clever, given the fact that I put + everything in memory before printing """ to_print = "" curr = self._root - to_print += str(curr.value) + to_print += str(curr.value) while(curr.nexti is not None): curr = curr.nexti to_print += ", " + str(curr.value) diff --git a/04_linkedList/ll_test.py b/04_linkedList/ll_test.py index 9c91264..c74d94c 100644 --- a/04_linkedList/ll_test.py +++ b/04_linkedList/ll_test.py @@ -5,6 +5,7 @@ Unit Tests for the Linked Lists implementations """ from ll import SingleListItem +from ll import SingleLinkedList import unittest @@ -22,9 +23,44 @@ class test_single_linked_list_item(unittest.TestCase): t = SingleListItem(12) self.assertEqual(False, t.has_next()) - + b = SingleListItem(13, t) self.assertEqual(True, b.has_next()) + +class test_single_linked_list(unittest.TestCase): + + def test_add(self): + a = 12 + sl = SingleLinkedList() + + sl.add(a) + self.assertEqual(1, len(sl)) + + sl.add(a) + self.assertEqual(2, len(sl)) + + def test_delete_item(self): + sl = SingleLinkedList() + + sl.add(1) + sl.add(2) + sl.add(3) + self.assertEqual(3, len(sl)) + + self.assertEqual(1, sl._root.value) + + self.assertRaises(Exception, lambda x : sl.delete_item(4)) + + sl.delete_item() + self.assertEqual(2, len(sl)) + self.assertEqual(2, sl._root.value) + + + sl.add(4) + sl.add(5) + sl.add(6) + print sl + if __name__ == "__main__": unittest.main()