Skip to content

Commit 85d5cac

Browse files
committed
24. Swap Nodes in Pairs.
- Language: Python. - Time complexity: O(n). - Space complexity: O(1). - Method: Swapping node using pointers.
1 parent cc32477 commit 85d5cac

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

python_solutions/lc_24_swap_nodes_in_pairs/lc_24_swap_nodes_in_pairs.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
class Solution:
77
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
88
# Time complexity: O(n). Space complexity: O(1).
9+
# Method: Data Overwriting.
910
if head is None:
1011
return head
1112
left, right = head, head.next
@@ -16,3 +17,17 @@ def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
1617
break
1718
right = left.next
1819
return head
20+
21+
def swapPairsV1(self, head: Optional[ListNode]) -> Optional[ListNode]:
22+
# Time complexity: O(n). Space complexity: O(1).
23+
# Method: Swapping node using pointers.
24+
dummy = ListNode(val=-1, next=head)
25+
prev, head = dummy, head
26+
while head is not None and head.next is not None:
27+
nxt = head.next
28+
prev.next = nxt
29+
head.next = nxt.next
30+
nxt.next = head
31+
prev = head
32+
head = head.next
33+
return dummy.next

python_solutions/lc_24_swap_nodes_in_pairs/test_lc_24_swap_nodes_in_pairs.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,13 @@ def test_success_v0(lst: list[int], ans: list[int], solution: Solution):
2828
assert compare_singly_linked_lists(res, to_singly_linked_list(ans))
2929

3030

31+
@pytest.mark.parametrize(("lst", "ans"), test_cases)
32+
def test_success_v1(lst: list[int], ans: list[int], solution: Solution):
33+
res = solution.swapPairsV1(to_singly_linked_list(lst))
34+
assert to_list(res) == ans
35+
assert compare_singly_linked_lists(res, to_singly_linked_list(ans))
36+
37+
3138
@pytest.fixture
3239
def solution() -> Solution:
3340
return Solution()

0 commit comments

Comments
 (0)