mirror of
https://hub.njuu.cf/TheAlgorithms/Python.git
synced 2023-10-11 13:06:12 +08:00
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:
parent
38d2e98665
commit
f9e0dd94d6
@ -106,6 +106,35 @@ class LinkedList:
|
|||||||
raise IndexError("Index out of range.")
|
raise IndexError("Index out of range.")
|
||||||
current = current.next
|
current = current.next
|
||||||
current.data = data
|
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():
|
def main():
|
||||||
@ -135,6 +164,7 @@ def main():
|
|||||||
A[1] = input("Enter New Value: ").strip()
|
A[1] = input("Enter New Value: ").strip()
|
||||||
print("New list:")
|
print("New list:")
|
||||||
print(A)
|
print(A)
|
||||||
|
print(f"length of A is : {len(A)}")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
Loading…
Reference in New Issue
Block a user