8000 added __len__ function · Pull Request #1812 · TheAlgorithms/Python · GitHub
[go: up one dir, main page]

Skip to content

added __len__ function #1812

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from May 18, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Add tests to __len__()
  • Loading branch information
cclauss authored May 18, 2020
commit 485b7d461c7554de47178b9708d2122bdac1db5b
31 changes: 25 additions & 6 deletions data_structures/linked_list/singly_linked_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,15 +108,34 @@ def __setitem__(self, index, data):
current.data = data

def __len__(self):
"""Return length of linked list i.e. number of nodes """
cur_node = self.head
"""
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

if not cur_node: return count #if list is empty
cur_node = self.head
while cur_node.next:
count+=1
count += 1
cur_node = cur_node.next
return count+1
return count + 1


def main():
A = LinkedList()
Expand Down
0