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