diff --git a/src/swap_nodes_in_pairs.py b/src/swap_nodes_in_pairs.py new file mode 100644 index 0000000..39fbec1 --- /dev/null +++ b/src/swap_nodes_in_pairs.py @@ -0,0 +1,22 @@ +from utils.linked_list import ListNode + + +class Solution: + def swapPairs(self, head: ListNode | None) -> ListNode | None: + dummy = ListNode(0) + dummy.next = head + + before = dummy + + while before.next and before.next.next: + a = before.next + b = a.next + after = b.next + + a.next = after + b.next = a + before.next = b + + before = a + + return dummy.next diff --git a/tests/test_swap_nodes_in_pairs.py b/tests/test_swap_nodes_in_pairs.py new file mode 100644 index 0000000..ee6d4d4 --- /dev/null +++ b/tests/test_swap_nodes_in_pairs.py @@ -0,0 +1,18 @@ +import pytest + +from src.swap_nodes_in_pairs import Solution +from src.utils.linked_list import to_linked_list +from src.utils.linked_list import to_list + + +@pytest.mark.parametrize( + "in_list,out_list", + ( + ([1, 2, 3, 4], [2, 1, 4, 3]), + ([], []), + ([1], [1]), + ), +) +def test_solution(in_list, out_list): + head = to_linked_list(in_list) + assert to_list(Solution().swapPairs(head)) == out_list