Skip to content

Remove extra len calls in doubly-linked-list's methods #8600

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 1 commit into from
Apr 1, 2023
Merged
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
14 changes: 9 additions & 5 deletions data_structures/linked_list/doubly_linked_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,9 @@ def insert_at_nth(self, index: int, data):
....
IndexError: list index out of range
"""
if not 0 <= index <= len(self):
length = len(self)

if not 0 <= index <= length:
raise IndexError("list index out of range")
new_node = Node(data)
if self.head is None:
Expand All @@ -90,7 +92,7 @@ def insert_at_nth(self, index: int, data):
self.head.previous = new_node
new_node.next = self.head
self.head = new_node
elif index == len(self):
elif index == length:
self.tail.next = new_node
new_node.previous = self.tail
self.tail = new_node
Expand Down Expand Up @@ -131,15 +133,17 @@ def delete_at_nth(self, index: int):
....
IndexError: list index out of range
"""
if not 0 <= index <= len(self) - 1:
length = len(self)

if not 0 <= index <= length - 1:
raise IndexError("list index out of range")
delete_node = self.head # default first node
if len(self) == 1:
if length == 1:
self.head = self.tail = None
elif index == 0:
self.head = self.head.next
self.head.previous = None
elif index == len(self) - 1:
elif index == length - 1:
delete_node = self.tail
self.tail = self.tail.previous
self.tail.next = None
Expand Down