Skip to content

Commit 321b142

Browse files
data_structures/linked_list: Add __len__() function and tests (#2047)
* Update __init__.py please add a function to get length of linked list * Update __init__.py * Update doubly_linked_list.py all size function lo doubly linked list class * prime number _better method * comments * Updated init.py 2 made it more pythonic * updated length function * commnet in linked_list construtor * Update data_structures/linked_list/__init__.py accepecting changes Co-authored-by: Christian Clauss <[email protected]> * Update data_structures/linked_list/__init__.py Co-authored-by: Christian Clauss <[email protected]> * Update __init__.py * Revert changes to doubly_linked_list.py * Revert changes to prime_check.py Co-authored-by: Christian Clauss <[email protected]>
1 parent 1e8fe8e commit 321b142

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

Diff for: data_structures/linked_list/__init__.py

+23
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,40 @@ def __init__(self, item, next):
77
class LinkedList:
88
def __init__(self):
99
self.head = None
10+
self.size = 0
1011

1112
def add(self, item):
1213
self.head = Node(item, self.head)
14+
self.size += 1
1315

1416
def remove(self):
1517
if self.is_empty():
1618
return None
1719
else:
1820
item = self.head.item
1921
self.head = self.head.next
22+
self.size -= 1
2023
return item
2124

2225
def is_empty(self):
2326
return self.head is None
27+
28+
def __len__(self):
29+
"""
30+
>>> linked_list = LinkedList()
31+
>>> len(linked_list)
32+
0
33+
>>> linked_list.add("a")
34+
>>> len(linked_list)
35+
1
36+
>>> linked_list.add("b")
37+
>>> len(linked_list)
38+
2
39+
>>> _ = linked_list.remove()
40+
>>> len(linked_list)
41+
1
42+
>>> _ = linked_list.remove()
43+
>>> len(linked_list)
44+
0
45+
"""
46+
return self.size

0 commit comments

Comments
 (0)