MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / add

Method add

data_structures/linked_list/__init__.py:25–75  ·  view source on GitHub ↗

Add an item to the LinkedList at the specified position. Default position is 0 (the head). Args: item (Any): The item to add to the LinkedList. position (int, optional): The position at which to add the item. Defaults to 0. R

(self, item: Any, position: int = 0)

Source from the content-addressed store, hash-verified

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

Callers 1

__iter__Method · 0.45

Calls 1

NodeClass · 0.70

Tested by

no test coverage detected