change space complexity of linked list's __len__ from O(n) to O(1) (#8183)

This commit is contained in:
amirsoroush 2023-04-01 09:26:43 +03:00 committed by GitHub
parent dc4f603dad
commit e4d90e2d5b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 4 additions and 4 deletions

View File

@ -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))

View File

@ -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)

View File

@ -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:
"""

View File

@ -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:
"""