题目描述
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
解题代码
func swapPairs(head *ListNode) *ListNode {
// 判断传进来的首元结点是否符合递归条件
if head == nil {
return nil
}
if head.Next == nil {
return head
}
// 第二个节点必定会变成首元节点
p := head.Next
swapPairsStep(head)
return p
}
func swapPairsStep(head *ListNode) *ListNode {
if head == nil {
return head
}
two := head.Next
if head.Next == nil {
return two
}
// 简单做一个返回值,因为上边的函数没有用到改返回值所以可以随便写
p := head
head.Next = head.Next.Next
two.Next = head
head.Next = swapPairs(head.Next)
return p
}