diff --git a/04_linkedList/ll.py b/04_linkedList/ll.py index 722a01a..f1d8d4a 100644 --- a/04_linkedList/ll.py +++ b/04_linkedList/ll.py @@ -147,7 +147,31 @@ class SingleLinkedList(): NOTE: This version does not store any extra data, but will take some extra time to complete """ - pass + # take root. + # look each element + # remove if same value + item = self._root + while(item.nexti != None): + next_item = item.nexti + self._remove_duplicate_light(item) + item = next_item + + def _remove_duplicate_light(self, element): + """ + Given an element in the list, removes all further duplicates of that + element in the remainder or the list. + """ + # edge case + if element is None: + return None + + val = element.value + while(element.nexti != None): + if(element.nexti.value == val): # duplicate + element.nexti = element.nexti.nexti + self._size -= 1 + else: # not duplicate + element = element.nexti def __len__(self): # Returns the number of elements in the list diff --git a/04_linkedList/ll_test.py b/04_linkedList/ll_test.py index 4eb4b0f..b6edcc5 100644 --- a/04_linkedList/ll_test.py +++ b/04_linkedList/ll_test.py @@ -148,6 +148,24 @@ class test_single_linked_list(unittest.TestCase): self.assertEqual(3, len(sl)) self.assertEqual("2, 1, 3", sl.__str__()) + def test_remove_duplicate_light(self): + + sl = SingleLinkedList() + + sl.add(2) + sl.add(1) + sl.add(3) + sl.add(2) + sl.add(3) + sl.add(1) + sl.add(2) + + self.assertEqual(7, len(sl)) + + sl._remove_duplicate_light(sl._root) + self.assertEqual(5, len(sl)) + self.assertEqual("2, 1, 3, 3, 1", sl.__str__()) + def test_remove_duplicates_light(self): sl = SingleLinkedList() @@ -162,7 +180,7 @@ class test_single_linked_list(unittest.TestCase): self.assertEqual(7, len(sl)) - sl.remove_duplicates() + sl.remove_duplicates_light() self.assertEqual(3, len(sl)) self.assertEqual("2, 1, 3", sl.__str__())