Skip to content

Commit

Permalink
"Swap Nodes in Pairs" solution
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Jun 15, 2024
1 parent e632379 commit 2af6926
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/swap_nodes_in_pairs.py
Original file line number Diff line number Diff line change
@@ -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
18 changes: 18 additions & 0 deletions tests/test_swap_nodes_in_pairs.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 2af6926

Please sign in to comment.