thiagowfx's avatar

¬ just serendipity 🍀 (not just serendipity)

LeetCode #24: Swap Nodes in Pairs

• 61 words • 1 min • updated

LeetCode #24: Swap Nodes in Pairs:

python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head or not head.next:
            return head

        first = head
        second = head.next
        third = head.next.next

        first.next = self.swapPairs(third)
        second.next = first

        return second