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. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-11 08:56:02       5 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-11 08:56:02       5 阅读
  3. 在Django里面运行非项目文件

    2024-06-11 08:56:02       4 阅读
  4. Python语言-面向对象

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

热门阅读

  1. xgboost导出为pmml模型包

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

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

    28.找零

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

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

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

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

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

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

    递归

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

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