Skip to content

data_structures/linked_list: Adding __str__() function #3960 #3961

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Nov 28, 2020
24 changes: 24 additions & 0 deletions data_structures/linked_list/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,30 @@ def remove(self):
def is_empty(self):
return self.head is None

def __str__(self):
"""
>>> linked_list = LinkedList()
>>> linked_list.add(23)
>>> linked_list.add(14)
>>> linked_list.add(9)
>>> print(linked_list)
9 --> 14 --> 23
"""
if not self.is_empty:
return "Linked List is empty."
else:
iterate = self.head
item_str = ""
item_list = []
while iterate:
item_list.append(iterate.item)
iterate = iterate.next

item_list = [str(item) for item in item_list]
item_str = " --> ".join(item_list)

return item_str

def __len__(self):
"""
>>> linked_list = LinkedList()
Expand Down