zl程序教程

您现在的位置是:首页 >  其他

当前栏目

每日一题---24. 两两交换链表中的节点[力扣][Go]

2023-03-14 22:58:35 时间

题目描述

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

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

解题代码

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
}

提交结果

image