mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
change space complexity of linked list's __len__ from O(n) to O(1) (#8183)
This commit is contained in:
parent
dc4f603dad
commit
e4d90e2d5b
|
@ -24,7 +24,7 @@ class CircularLinkedList:
|
|||
break
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(tuple(iter(self)))
|
||||
return sum(1 for _ in self)
|
||||
|
||||
def __repr__(self):
|
||||
return "->".join(str(item) for item in iter(self))
|
||||
|
|
|
@ -51,7 +51,7 @@ class DoublyLinkedList:
|
|||
>>> len(linked_list) == 5
|
||||
True
|
||||
"""
|
||||
return len(tuple(iter(self)))
|
||||
return sum(1 for _ in self)
|
||||
|
||||
def insert_at_head(self, data):
|
||||
self.insert_at_nth(0, data)
|
||||
|
|
|
@ -44,7 +44,7 @@ class SortedLinkedList:
|
|||
>>> len(SortedLinkedList(test_data_odd))
|
||||
8
|
||||
"""
|
||||
return len(tuple(iter(self)))
|
||||
return sum(1 for _ in self)
|
||||
|
||||
def __str__(self) -> str:
|
||||
"""
|
||||
|
|
|
@ -72,7 +72,7 @@ class LinkedList:
|
|||
>>> len(linked_list)
|
||||
0
|
||||
"""
|
||||
return len(tuple(iter(self)))
|
||||
return sum(1 for _ in self)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
"""
|
||||
|
|
Loading…
Reference in New Issue
Block a user