Starts implementing the delete_item method, that deletes the nth element from the list

This commit is contained in:
julien lengrand-lambert
2013-12-08 14:32:05 +01:00
parent e8a03abf8d
commit c64ae01a36
2 changed files with 61 additions and 8 deletions

View File

@@ -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)

View File

@@ -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()