题目
给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。
你不需要 保留 每个分区中各节点的初始相对位置。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/partition-list-lcci
eg:取链表 是[4,2,1,6,8,0,7,5],x=5.
思路
1.利用一个指针cur,遍历原链表,将cur->val与x值进行大小比较。
2.把小于x的放在一个链表,把其他放在另一个新的链表。然后再把两个链表连接起来。(利用哨兵头)
3.当cur走到空,说明结束了
注意考虑极端场景
1.链表为空。最开始将哨兵的next初始化为null;或者在循环结束时,将尾节点的next置空(因为链表为空,就不会进入循环,最后返回的是lessguard->next)
2.有一种情况需要注意,tailgreat->会指向其他结点,所以最后需要进行单独处理。
2.注意一种情况
图示展示过程:
代码
struct ListNode* partition(struct ListNode* head, int x){
// write code here
//用来尾插小于等于X的
struct ListNode* lessguard=(struct ListNode*)malloc(sizeof(struct ListNode));
//用来尾插大于X的
struct ListNode* greatguard=(struct ListNode*)malloc(sizeof(struct ListNode));
lessguard->next=NULL;
greatguard->next=NULL;
struct ListNode* tailless=lessguard;//标记小于X链表的尾结点
struct ListNode* tailgreat=greatguard;//标记大于X链表的尾结点
struct ListNode* cur=head;
while(cur)
{
if(cur->val<x)
{
//尾插到tailless后面
tailless->next=cur;
//更新尾结点
tailless=tailless->next;
}
else
{
tailgreat->next=cur;
tailgreat=tailgreat->next;
}
cur=cur->next;
}
tailless->next=greatguard->next;
tailgreat->next=NULL;
head=lessguard->next;
//释放空间
free(lessguard);
free(greatguard);
return head;
}