美文网首页
leetcode 24. 两两交换链表中的节点

leetcode 24. 两两交换链表中的节点

作者: fanchuang | 来源:发表于2020-02-11 18:48 被阅读0次

这道题的解法也很经典,执行效率也很不错

提交结果.png
class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        
        # 给定 1->2->3->4, 你应该返回 2->1->4->3.
        
        # 递归。下面这种递归的写法我有点难以理解。也许是命名,也许是写法上。
        # 1. 找终结条件
        # if not head or not head.next:
        #     return head 

        # first = head 
        # second = head.next 

        # # 3. 单次递归的过程。 
        # first.next = self.swapPairs(second.next)
        # second.next = first 

        # return second   # 2. 找返回值。应该是已经交换完成后的子链表。



        # 2. 另一种递归的写法,我觉得是很清晰明了。
        if not head or not head.next:
            return head 
        else:
            head, head.next, head.next.next = head.next, head, self.swapPairs(head.next.next)
            return head

相关文章

网友评论

      本文标题:leetcode 24. 两两交换链表中的节点

      本文链接:https://www.haomeiwen.com/subject/oxtffhtx.html