LeetCode 题解工作台
排序链表
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。 示例 1: 输入: head = [4,2,1,3] 输出: [1,2,3,4] 示例 2: 输入: head = [-1,5,3,4,0] 输出: [-1,0,3,4,5] 示例 3: 输入: head = [] 输出: …
5
题型
8
代码语言
3
相关题
当前训练重点
中等 · 链表指针操作
答案摘要
我们可以用归并排序的思想来解决。 首先,我们利用快慢指针找到链表的中点,将链表从中点处断开,形成两个独立的子链表 和 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路
题目描述
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
示例 1:
输入:head = [4,2,1,3] 输出:[1,2,3,4]
示例 2:
输入:head = [-1,5,3,4,0] 输出:[-1,0,3,4,5]
示例 3:
输入:head = [] 输出:[]
提示:
- 链表中节点的数目在范围
[0, 5 * 104]内 -105 <= Node.val <= 105
进阶:你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
解题思路
方法一:归并排序
我们可以用归并排序的思想来解决。
首先,我们利用快慢指针找到链表的中点,将链表从中点处断开,形成两个独立的子链表 和 。
然后,我们递归地对 和 进行排序,最后将 和 合并为一个有序链表。
时间复杂度 ,空间复杂度 。其中 是链表的长度。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None or head.next is None:
return head
slow, fast = head, head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
l1, l2 = head, slow.next
slow.next = None
l1, l2 = self.sortList(l1), self.sortList(l2)
dummy = ListNode()
tail = dummy
while l1 and l2:
if l1.val <= l2.val:
tail.next = l1
l1 = l1.next
else:
tail.next = l2
l2 = l2.next
tail = tail.next
tail.next = l1 or l2
return dummy.next
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n log n) due to the divide-and-conquer merge sort approach. Space complexity is O(log n) for recursion stack; no additional arrays are used, keeping pointer manipulation efficient. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The interviewer may hint at avoiding array conversion for true pointer manipulation.
- question_mark
Expect discussion on fast and slow pointers for splitting the linked list.
- question_mark
They often ask how to merge sublists without extra space to verify understanding of linked-list operations.
常见陷阱
外企场景- error
Accidentally creating cycles when reconnecting nodes during merge.
- error
Not handling empty lists or single-node lists as base cases, causing null pointer errors.
- error
Failing to update head or tail pointers correctly, leading to lost nodes in the final sorted list.
进阶变体
外企场景- arrow_right_alt
Sort a doubly linked list using similar divide-and-conquer strategies but with backward pointers.
- arrow_right_alt
Sort a linked list where nodes contain extra data that must remain paired with values.
- arrow_right_alt
Implement iterative bottom-up merge sort instead of recursive sorting to reduce stack usage.