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

Class LinkedList

data_structures/linked_list/swap_nodes.py:15–131  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

13
14@dataclass
15class LinkedList:
16 head: Node | None = None
17
18 def __iter__(self) -> Iterator:
19 """
20 >>> linked_list = LinkedList()
21 >>> list(linked_list)
22 []
23 >>> linked_list.push(0)
24 >>> tuple(linked_list)
25 (0,)
26 """
27 node = self.head
28 while node:
29 yield node.data
30 node = node.next_node
31
32 def __len__(self) -> int:
33 """
34 >>> linked_list = LinkedList()
35 >>> len(linked_list)
36 0
37 >>> linked_list.push(0)
38 >>> len(linked_list)
39 1
40 """
41 return sum(1 for _ in self)
42
43 def push(self, new_data: Any) -> None:
44 """
45 Add a new node with the given data to the beginning of the Linked List.
46
47 Args:
48 new_data (Any): The data to be added to the new node.
49
50 Returns:
51 None
52
53 Examples:
54 >>> linked_list = LinkedList()
55 >>> linked_list.push(5)
56 >>> linked_list.push(4)
57 >>> linked_list.push(3)
58 >>> linked_list.push(2)
59 >>> linked_list.push(1)
60 >>> list(linked_list)
61 [1, 2, 3, 4, 5]
62 """
63 new_node = Node(new_data)
64 new_node.next_node = self.head
65 self.head = new_node
66
67 def swap_nodes(self, node_data_1: Any, node_data_2: Any) -> None:
68 """
69 Swap the positions of two nodes in the Linked List based on their data values.
70
71 Args:
72 node_data_1: Data value of the first node to be swapped.

Callers 1

swap_nodes.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected