Skip to content

Added length instance Variable in singly_linked_list to keep track of length while addition/deletion #5320

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

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
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
7 changes: 4 additions & 3 deletions data_structures/linked_list/singly_linked_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def __repr__(self):
class LinkedList:
def __init__(self):
self.head = None

self.length = 0
def __iter__(self):
node = self.head
while node:
Expand All @@ -36,8 +36,7 @@ def __len__(self) -> int:
>>> len(linked_list)
0
"""
return len(tuple(iter(self)))

return self.length
def __repr__(self):
"""
String representation/visualization of a Linked Lists
Expand Down Expand Up @@ -116,6 +115,7 @@ def insert_nth(self, index: int, data) -> None:
temp = temp.next
new_node.next = temp.next
temp.next = new_node
self.length += 1

def print_list(self) -> None: # print every node data
print(self)
Expand All @@ -138,6 +138,7 @@ def delete_nth(self, index: int = 0):
temp = temp.next
delete_node = temp.next
temp.next = temp.next.next
self.length -= 1
return delete_node.data

def is_empty(self) -> bool:
Expand Down