LeetCode 题解工作台
分隔链表
给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。 你应当 保留 两个分区中每个节点的初始相对位置。 示例 1: 输入: head = [1,4,3,2,5,2], x = 3 输出 :[1,2,2,4,3,5] …
2
题型
8
代码语言
3
相关题
当前训练重点
中等 · 链表指针操作
答案摘要
我们创建两个链表 和 ,一个用来存储小于 的节点,另一个用来存储大于等于 的节点。然后我们将它们拼接起来。 时间复杂度 ,其中 是原链表的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路
题目描述
给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。
你应当 保留 两个分区中每个节点的初始相对位置。
示例 1:
输入:head = [1,4,3,2,5,2], x = 3 输出:[1,2,2,4,3,5]
示例 2:
输入:head = [2,1], x = 2 输出:[1,2]
提示:
- 链表中节点的数目在范围
[0, 200]内 -100 <= Node.val <= 100-200 <= x <= 200
解题思路
方法一:模拟
我们创建两个链表 和 ,一个用来存储小于 的节点,另一个用来存储大于等于 的节点。然后我们将它们拼接起来。
时间复杂度 ,其中 是原链表的长度。空间复杂度 。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
l = ListNode()
r = ListNode()
tl, tr = l, r
while head:
if head.val < x:
tl.next = head
tl = tl.next
else:
tr.next = head
tr = tr.next
head = head.next
tr.next = None
tl.next = r.next
return l.next
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate effectively uses pointer manipulation to solve the problem.
- question_mark
Candidate correctly handles edge cases like empty lists or all nodes falling in one partition.
- question_mark
Solution demonstrates knowledge of linked-list traversal and node manipulation.
常见陷阱
外企场景- error
Failing to preserve the relative order of nodes within each partition.
- error
Incorrectly linking the 'less than x' partition to the 'greater than or equal to x' partition.
- error
Not considering edge cases like empty lists or lists where all nodes fall into one partition.
进阶变体
外企场景- arrow_right_alt
Modify the problem to handle circular linked lists.
- arrow_right_alt
Partition the list in place using constant space.
- arrow_right_alt
Extend the problem by adding multiple partitions around different values.