题目描述
给你一个链表的头节点 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 的节点在前,大于或等于 x 的节点在后。关键点在于不需要保持每个分区内节点的原始相对顺序。
核心思想
使用双指针方法:
- 对于小于 x 的节点,采用头插法插入到新链表头部
- 对于大于等于 x 的节点,采用尾插法插入到新链表尾部
- 这样就能保证所有小于 x 的节点都在大于等于 x 的节点之前
代码实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* partition(struct ListNode* head, int x) {
struct ListNode* cur = head;
struct ListNode* newhead = NULL;
struct ListNode* newtail = NULL;
struct ListNode* temp = NULL;
while(cur) {
temp = cur->next; // 保存下一个节点
if(cur->val < x) { // 小于x的节点:头插法
if(newhead == NULL) {
newhead = newtail = cur;
newhead->next = NULL;
} else {
cur->next = newhead;
newhead = cur;
}
} {
(newhead == ) {
newhead = newtail = cur;
newhead->next = ;
} {
newtail->next = cur;
newtail = cur;
newtail->next = ;
}
}
cur = temp;
}
newhead;
}


