题目

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例:

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

方案一(递归)

  1. /**
  2. * Definition for singly-linked list.
  3. * type ListNode struct {
  4. * Val int
  5. * Next *ListNode
  6. * }
  7. */
  8. func swapPairs(head *ListNode) *ListNode {
  9. if head == nil || head.Next == nil {
  10. return head
  11. }
  12. // 调整指针
  13. next := head.Next
  14. next_next := head.Next.Next
  15. next.Next = head
  16. head.Next = next_next
  17. head.Next = swapPairs(next_next)
  18. return next
  19. }

原文

https://leetcode-cn.com/explore/featured/card/recursion-i/256/principle-of-recursion/1201/