Skip to content

Added an add at position subroutiune to linked list #9020

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 14 commits into from
Sep 8, 2023
Merged
Changes from 2 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
35 changes: 35 additions & 0 deletions data_structures/linked_list/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,41 @@ def add(self, item: Any) -> None:
self.head = Node(item, self.head)
self.size += 1

def add_at_position(self, item: Any, position: int) -> bool:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about insert_at_position?

"""
Adds a new node with the given item at the specified position in the linked list

Args:
item (Any): The item to be added to the linked list.
position (int): The position at which the item should be inserted.

Returns:
bool: True if the insertion was successful, False otherwise.

>>> linked_list = LinkedList()
>>> linked_list.add(1)
>>> linked_list.add(2)
>>> linked_list.add(3)
>>> linked_list.add_at_position(10, 1)
True

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here there should be a test displaying linked_list

"""
if position < 0:
return False
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe this should raise an error?

Suggested change
if position < 0:
return False
if 0 > position:
return False

This also looks a bit more readable


current = self.head
counter = 0
while current and counter < position:
current = current.next
counter += 1

if current: # Check if current is not None
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if current: # Check if current is not None
if current is not None:

new_node = Node(item, current.next)
current.next = new_node
return True
else:
return False
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
else:
return False
return False


def remove(self) -> Any:
# Switched 'self.is_empty()' to 'self.head is None'
# because mypy was considering the possibility that 'self.head'
Expand Down