Skip to content

Commit 38d5efb

Browse files
mendacium-a11ysedatguzelsemme
authored andcommitted
Added an add at position subroutiune to linked list (TheAlgorithms#9020)
* added addAtPosition to simple linked list * added addAtPosition to simple linked list * modified the add function to take an optional position command * fixed type safety errors: * fixed type safety errors: * fixed type safety errors: * fixed type safety errors: * fixed size error * fixed size error * added doctest and updates the else after checking if posiiton argument less than 0 or not * added doctest and updates the else after checking if posiiton argument less than 0 or not * fixed the contributing.md mistake * added doctest for out of bounds position value, both negative and positive
1 parent 3cc035a commit 38d5efb

File tree

1 file changed

+50
-2
lines changed

1 file changed

+50
-2
lines changed

Diff for: data_structures/linked_list/__init__.py

+50-2
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,56 @@ def __init__(self) -> None:
2121
self.head: Node | None = None
2222
self.size = 0
2323

24-
def add(self, item: Any) -> None:
25-
self.head = Node(item, self.head)
24+
def add(self, item: Any, position: int = 0) -> None:
25+
"""
26+
Add an item to the LinkedList at the specified position.
27+
Default position is 0 (the head).
28+
29+
Args:
30+
item (Any): The item to add to the LinkedList.
31+
position (int, optional): The position at which to add the item.
32+
Defaults to 0.
33+
34+
Raises:
35+
ValueError: If the position is negative or out of bounds.
36+
37+
>>> linked_list = LinkedList()
38+
>>> linked_list.add(1)
39+
>>> linked_list.add(2)
40+
>>> linked_list.add(3)
41+
>>> linked_list.add(4, 2)
42+
>>> print(linked_list)
43+
3 --> 2 --> 4 --> 1
44+
45+
# Test adding to a negative position
46+
>>> linked_list.add(5, -3)
47+
Traceback (most recent call last):
48+
...
49+
ValueError: Position must be non-negative
50+
51+
# Test adding to an out-of-bounds position
52+
>>> linked_list.add(5,7)
53+
Traceback (most recent call last):
54+
...
55+
ValueError: Out of bounds
56+
>>> linked_list.add(5, 4)
57+
>>> print(linked_list)
58+
3 --> 2 --> 4 --> 1 --> 5
59+
"""
60+
if position < 0:
61+
raise ValueError("Position must be non-negative")
62+
63+
if position == 0 or self.head is None:
64+
new_node = Node(item, self.head)
65+
self.head = new_node
66+
else:
67+
current = self.head
68+
for _ in range(position - 1):
69+
current = current.next
70+
if current is None:
71+
raise ValueError("Out of bounds")
72+
new_node = Node(item, current.next)
73+
current.next = new_node
2674
self.size += 1
2775

2876
def remove(self) -> Any:

0 commit comments

Comments
 (0)