Swap the positions of two nodes in the Linked List based on their data values. Args: node_data_1: Data value of the first node to be swapped. node_data_2: Data value of the second node to be swapped. Note: If either of the spec
(self, node_data_1: Any, node_data_2: Any)
| 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. |
| 73 | node_data_2: Data value of the second node to be swapped. |
| 74 | |
| 75 | |
| 76 | Note: |
| 77 | If either of the specified data values isn't found then, no swapping occurs. |
| 78 | |
| 79 | Examples: |
| 80 | When both values are present in a linked list. |
| 81 | >>> linked_list = LinkedList() |
| 82 | >>> linked_list.push(5) |
| 83 | >>> linked_list.push(4) |
| 84 | >>> linked_list.push(3) |
| 85 | >>> linked_list.push(2) |
| 86 | >>> linked_list.push(1) |
| 87 | >>> list(linked_list) |
| 88 | [1, 2, 3, 4, 5] |
| 89 | >>> linked_list.swap_nodes(1, 5) |
| 90 | >>> tuple(linked_list) |
| 91 | (5, 2, 3, 4, 1) |
| 92 | |
| 93 | When one value is present and the other isn't in the linked list. |
| 94 | >>> second_list = LinkedList() |
| 95 | >>> second_list.push(6) |
| 96 | >>> second_list.push(7) |
| 97 | >>> second_list.push(8) |
| 98 | >>> second_list.push(9) |
| 99 | >>> second_list.swap_nodes(1, 6) is None |
| 100 | True |
| 101 | |
| 102 | When both values are absent in the linked list. |
| 103 | >>> second_list = LinkedList() |
| 104 | >>> second_list.push(10) |
| 105 | >>> second_list.push(9) |
| 106 | >>> second_list.push(8) |
| 107 | >>> second_list.push(7) |
| 108 | >>> second_list.swap_nodes(1, 3) is None |
| 109 | True |
| 110 | |
| 111 | When linkedlist is empty. |
| 112 | >>> second_list = LinkedList() |
| 113 | >>> second_list.swap_nodes(1, 3) is None |
| 114 | True |
| 115 | |
| 116 | Returns: |
| 117 | None |
| 118 | """ |
| 119 | if node_data_1 == node_data_2: |
| 120 | return |
| 121 | |
| 122 | node_1 = self.head |
| 123 | while node_1 and node_1.data != node_data_1: |
| 124 | node_1 = node_1.next_node |