Skip to content
Merged
Changes from 3 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
29 changes: 18 additions & 11 deletions data_structures/linked_list/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ def add(self, item: Any, position: int = 0) -> None:
Args:
item (Any): The item to add to the LinkedList.
position (int, optional): The position at which to add the item.
Defaults to 0.
Defaults to 0.

Raises:
ValueError: If the position is negative.
ValueError: If the position is negative or out of bounds.

>>> linked_list = LinkedList()
>>> linked_list.add(1)
Expand All @@ -41,6 +41,17 @@ def add(self, item: Any, position: int = 0) -> None:
>>> linked_list.add(4, 2)
>>> print(linked_list)
3 --> 2 --> 4 --> 1

# Test adding to a negative position
>>> linked_list.add(5, -3)
Traceback (most recent call last):
...
ValueError: Position must be non-negative

# Test adding to an out-of-bounds position
>>> linked_list.add(5, 4)
>>> print(linked_list)
3 --> 2 --> 4 --> 1 --> 5
"""
if position < 0:
raise ValueError("Position must be non-negative")
Expand All @@ -50,16 +61,12 @@ def add(self, item: Any, position: int = 0) -> None:
self.head = new_node
else:
current = self.head
counter = 0
while current and counter < position - 1:
for _ in range(position - 1):
current = current.next
counter += 1

if current: # Check if current is not None
new_node = Node(item, current.next)
current.next = new_node
else:
raise ValueError("Out of bounds")
if current is None:
raise ValueError("Out of bounds")
new_node = Node(item, current.next)
current.next = new_node
self.size += 1

def remove(self) -> Any:
Expand Down