From f9e0dd94d6040cd41b1272e8a6ece34dc767152e Mon Sep 17 00:00:00 2001 From: Akash Date: Mon, 18 May 2020 21:40:55 +0530 Subject: [PATCH] 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 --- .../linked_list/singly_linked_list.py | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/data_structures/linked_list/singly_linked_list.py b/data_structures/linked_list/singly_linked_list.py index c90cfb6e5..516facc61 100644 --- a/data_structures/linked_list/singly_linked_list.py +++ b/data_structures/linked_list/singly_linked_list.py @@ -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__":