Python | Leetcode Python题解之第143题重排链表

题目:

题解:

class Solution:
    def reorderList(self, head: ListNode) -> None:
        if not head:
            return
        
        mid = self.middleNode(head)
        l1 = head
        l2 = mid.next
        mid.next = None
        l2 = self.reverseList(l2)
        self.mergeList(l1, l2)
    
    def middleNode(self, head: ListNode) -> ListNode:
        slow = fast = head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
        return slow
    
    def reverseList(self, head: ListNode) -> ListNode:
        prev = None
        curr = head
        while curr:
            nextTemp = curr.next
            curr.next = prev
            prev = curr
            curr = nextTemp
        return prev

    def mergeList(self, l1: ListNode, l2: ListNode):
        while l1 and l2:
            l1_tmp = l1.next
            l2_tmp = l2.next

            l1.next = l2
            l1 = l1_tmp

            l2.next = l1
            l2 = l2_tmp

相关推荐

最近更新

  1. 安卓gradel下载失败解决方案

    2024-06-11 08:56:02       0 阅读
  2. 实战

    实战

    2024-06-11 08:56:02      0 阅读
  3. 力扣719.找出第K小的数对距离

    2024-06-11 08:56:02       0 阅读
  4. 10月,2024北京养老展,北京老年生活用品展览会

    2024-06-11 08:56:02       0 阅读
  5. python之面向对象编程

    2024-06-11 08:56:02       0 阅读
  6. Python2.7中os.path模块常用函数记录

    2024-06-11 08:56:02       0 阅读

热门阅读

  1. xgboost导出为pmml模型包

    2024-06-11 08:56:02       4 阅读
  2. 回溯算法练习题(2024/6/10)

    2024-06-11 08:56:02       4 阅读
  3. 28.找零

    28.找零

    2024-06-11 08:56:02      3 阅读
  4. Kubernetes学习总结知识点汇总

    2024-06-11 08:56:02       3 阅读
  5. hw meta10 adb back up DCIM

    2024-06-11 08:56:02       6 阅读
  6. 【Spring Boot】过滤敏感词的两种实现

    2024-06-11 08:56:02       4 阅读
  7. 鼠标侧键映射虚拟桌面切换 —— Win11

    2024-06-11 08:56:02       4 阅读
  8. YOLOv5的predict.py逐句讲解(学习笔记)

    2024-06-11 08:56:02       4 阅读
  9. 递归

    递归

    2024-06-11 08:56:02      6 阅读
  10. OpenZeppelin Ownable合约 怎么使用

    2024-06-11 08:56:02       3 阅读