Leetcode - 24 两两交换链表中的节点 python

版权声明:本文章为原创,未经许可不得转载 https://blog.csdn.net/weixin_41864878/article/details/91362046

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

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

示例:

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

这一题关于递归的写法,看看热评那位大佬的博客就一目了然,地址:http://lylblog.cn/blog/4
我把核心的思路图贴过来
在这里插入图片描述
这道题其实一般都会宏观的考虑成head head.next head.next.next这三个节点,首先肯定是要交换前两个节点的地址的,对于第三个节点我的理解就是运用递归的时候, 它就是递归函数的返回结果,所以交换后的head.next = function(head.next.next)

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next: return head
        node = head.next
        head.next = self.swapPairs(node.next)
        node.next = head
        return node

猜你喜欢

转载自blog.csdn.net/weixin_41864878/article/details/91362046