143. 重排链表

题目链接 143. 重排链表
思路 链表综合题:快慢指针(找链表一半位置)+ 链表翻转
题解链接 【视频】没想明白?一个视频讲透!(Python/Java/C++/Go/JS)
关键点 快慢指针:while fast and fast.next: ... && 合并时结束条件:while second.next: ...
时间复杂度 \(O(n)\)
空间复杂度 \(O(1)\)

代码实现:

class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        second = self.halfList(head)
        second = self.reverseList(second)
        
        while second.next:
            next_node_1 = head.next
            next_node_2 = second.next
            head.next = second
            second.next = next_node_1
            head = next_node_1
            second = next_node_2
        
    def halfList(self, head):
        slow = fast = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
        return slow
    
    def reverseList(self, head):
        previous = None
        current = head
        while current:
            next_node = current.next
            current.next = previous
            previous = current
            current = next_node
        return previous
posted @   WrRan  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示