24. 两两交换链表中的节点

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.

递归

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6. class Solution:
  7. def swapPairs(self, head: ListNode) -> ListNode:
  8. if not head or not head.next:
  9. return head
  10. Next = head.next
  11. head.next = self.swapPairs(Next.next)
  12. Next.next = head
  13. return Next