24. Swap nodes in pairs

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list’s nodes (i.e., only nodes themselves may be changed.)

Example 1: Input: head = [1,2,3,4] Output: [2,1,4,3]


  • code
class Solution:
    def swapPairs(self, head):
        res = pre = ListNode()
        pre.next = head
        while pre.next and pre.next.next:
            first = pre.next
            second = pre.next.next
            pre.next, second.next, first.next = second, first, second.next
            # pre = a
            pre = pre.next.next
        return res.next
  • code
class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head

        def helper(node):
            if not node or not node.next:
                return node
            rest = node.next.next
            nexNode = node.next
            node.next.next = node
            node.next = helper(rest)
            return nexNode

        return helper(head)