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

递归

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func swapPairs(head *ListNode) *ListNode {
    // 定义:输入以 head 开头的单链表,将这个单链表中的每两个元素翻转,
    // 返回翻转后的链表头结点
    if head==nil || head.Next==nil{
        return head
    }
    first :=head
    second:= head.Next
    other:=head.Next.Next
    // 先把前两个元素翻转
    second.Next=first
    // 利用递归定义,将剩下的链表节点两两翻转,接到后面
    first.Next=swapPairs(other)
    // 现在整个链表都成功翻转了,返回新的头结点
    return second   
}

Last updated