Skip to content

Commit d101466

Browse files
arif599amaank404
authored andcommitted
data_structures/linked_list: Add __str__() function (TheAlgorithms#3961)
* Adding __str__() function * Removing white space * Update data_structures/linked_list/__init__.py Co-authored-by: xcodz-dot <[email protected]> * Adding type hints * Update __init__.py * Update __init__.py * Adding the changes requested * Updating to fix pre-commit * Updating __init__.py * Updating __init__.py Co-authored-by: xcodz-dot <[email protected]>
1 parent 6de47fb commit d101466

File tree

1 file changed

+40
-6
lines changed

1 file changed

+40
-6
lines changed

Diff for: data_structures/linked_list/__init__.py

+40-6
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,30 @@
1+
"""
2+
Linked Lists consists of Nodes.
3+
Nodes contain data and also may link to other nodes:
4+
- Head Node: First node, the address of the
5+
head node gives us access of the complete list
6+
- Last node: points to null
7+
"""
8+
9+
from typing import Any
10+
11+
112
class Node:
2-
def __init__(self, item, next):
13+
def __init__(self, item: Any, next: Any) -> None:
314
self.item = item
415
self.next = next
516

617

718
class LinkedList:
8-
def __init__(self):
19+
def __init__(self) -> None:
920
self.head = None
1021
self.size = 0
1122

12-
def add(self, item):
23+
def add(self, item: Any) -> None:
1324
self.head = Node(item, self.head)
1425
self.size += 1
1526

16-
def remove(self):
27+
def remove(self) -> Any:
1728
if self.is_empty():
1829
return None
1930
else:
@@ -22,10 +33,33 @@ def remove(self):
2233
self.size -= 1
2334
return item
2435

25-
def is_empty(self):
36+
def is_empty(self) -> bool:
2637
return self.head is None
2738

28-
def __len__(self):
39+
def __str__(self) -> str:
40+
"""
41+
>>> linked_list = LinkedList()
42+
>>> linked_list.add(23)
43+
>>> linked_list.add(14)
44+
>>> linked_list.add(9)
45+
>>> print(linked_list)
46+
9 --> 14 --> 23
47+
"""
48+
if not self.is_empty:
49+
return ""
50+
else:
51+
iterate = self.head
52+
item_str = ""
53+
item_list = []
54+
while iterate:
55+
item_list.append(str(iterate.item))
56+
iterate = iterate.next
57+
58+
item_str = " --> ".join(item_list)
59+
60+
return item_str
61+
62+
def __len__(self) -> int:
2963
"""
3064
>>> linked_list = LinkedList()
3165
>>> len(linked_list)

0 commit comments

Comments
 (0)