150强访谈简单

重新排序列表

“重新排序列表”问题的详细指南和 Python 实现。

问题陈述

简单

给你一个单链表的头。该列表可以表示为:

L0 → L1 → … → Ln-1 → Ln

将列表重新排序为以下形式:

L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …

您不能修改列表节点中的值。只能更改节点本身。

链接列表表示为 Python 列表。实现一个函数 reorderList(head: list) -> list 返回重新排序的列表。

约束条件
  • The number of nodes in the list is in the range [1, 50000]
  • 1 <= Node.val <= 1000

示例

Example 1
Input
[1,2,3,4]
Output
[1,4,2,3]
Explanation

The list 1->2->3->4 is reordered to 1->4->2->3.

Example 2
Input
[1,2,3,4,5]
Output
[1,5,2,4,3]
Explanation

The list 1->2->3->4->5 is reordered to 1->5->2->4->3.

Need a Hint?
考虑使用特定于链接列表的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。