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
20 changes: 20 additions & 0 deletions data_structures/linked_list/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,26 @@ 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
iteam_str = ""
while iterate:
iteam_str += f"{iterate.item} --> "
iterate = iterate.next

return iteam_str

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