added __len__ function (#1812)

* added __len__ function

Added a function to count number of nodes in linked list

* Updated __len__ method

used snake_case instead of camel case

* Add tests to __len__()

Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
Akash 2020-05-18 21:40:55 +05:30 committed by GitHub
parent 38d2e98665
commit f9e0dd94d6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -106,6 +106,35 @@ class LinkedList:
raise IndexError("Index out of range.")
current = current.next
current.data = data
def __len__(self):
"""
Return length of linked list i.e. number of nodes
>>> linked_list = LinkedList()
>>> len(linked_list)
0
>>> linked_list.insert_tail("head")
>>> len(linked_list)
1
>>> linked_list.insert_head("head")
>>> len(linked_list)
2
>>> _ = linked_list.delete_tail()
>>> len(linked_list)
1
>>> _ = linked_list.delete_head()
>>> len(linked_list)
0
"""
if not self.head:
return 0
count = 0
cur_node = self.head
while cur_node.next:
count += 1
cur_node = cur_node.next
return count + 1
def main():
@ -135,6 +164,7 @@ def main():
A[1] = input("Enter New Value: ").strip()
print("New list:")
print(A)
print(f"length of A is : {len(A)}")
if __name__ == "__main__":