implements the print method

This commit is contained in:
Julien Lengrand-Lambert
2013-12-07 16:20:46 +01:00
parent 757e3cbcd0
commit e8a03abf8d

View File

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