Medium
题目描述
给你一个链表的头节点 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
解题思路
解题思路
这道题要求将链表按照给定值 x 进行分隔,保持原有的相对顺序不变。
双指针法(推荐)
核心思想是创建两个新的链表:
smallHead:存储所有小于 x 的节点largeHead:存储所有大于等于 x 的节点
算法步骤:
- 创建两个虚拟头节点
smallHead和largeHead,以及对应的尾指针small和large - 遍历原链表,根据节点值与 x 的关系,将节点分别连接到对应的链表上
- 遍历完成后,将小链表的尾部连接到大链表的头部
- 将大链表的尾部置为
null,避免形成环 - 返回小链表的头节点(跳过虚拟头节点)
这种方法的优点是逻辑清晰,代码简洁,且只需要一次遍历就能完成分隔。
时间复杂度为 O(n),空间复杂度为 O(1)(只使用了常数个额外指针)。
代码实现
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode smallHead(0), largeHead(0);
ListNode* small = &smallHead;
ListNode* large = &largeHead;
while (head) {
if (head->val < x) {
small->next = head;
small = small->next;
} else {
large->next = head;
large = large->next;
}
head = head->next;
}
large->next = nullptr;
small->next = largeHead.next;
return smallHead.next;
}
};
class Solution:
def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
small_head = ListNode(0)
large_head = ListNode(0)
small = small_head
large = large_head
while head:
if head.val < x:
small.next = head
small = small.next
else:
large.next = head
large = large.next
head = head.next
large.next = None
small.next = large_head.next
return small_head.next
public class Solution {
public ListNode Partition(ListNode head, int x) {
ListNode smallHead = new ListNode(0);
ListNode largeHead = new ListNode(0);
ListNode small = smallHead;
ListNode large = largeHead;
while (head != null) {
if (head.val < x) {
small.next = head;
small = small.next;
} else {
large.next = head;
large = large.next;
}
head = head.next;
}
large.next = null;
small.next = largeHead.next;
return smallHead.next;
}
}
var partition = function(head, x) {
const smallHead = new ListNode(0);
const largeHead = new ListNode(0);
let small = smallHead;
let large = largeHead;
while (head) {
if (head.val < x) {
small.next = head;
small = small.next;
} else {
large.next = head;
large = large.next;
}
head = head.next;
}
large.next = null;
small.next = largeHead.next;
return smallHead.next;
};
复杂度分析
| 复杂度类型 | 复杂度 | 说明 |
|---|---|---|
| 时间复杂度 | O(n) | 需要遍历链表一次,n 为链表长度 |
| 空间复杂度 | O(1) | 只使用了常数个额外指针变量 |