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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库