思路
双指针加插入方法进行解题
解题方法
第一步,定义四个指针:big,small,p,dummy。big指针用于指向第一个大于或等于x的结点的前一个结点。small指针用于寻找小于x的结点,它指向小于x的结点的前一个结点。p用于插入。dummy指针用于创建虚拟结点。
第二步,利用循环来找到第一个big结点。并让small结点从big->next结点开始遍历。依次将符合条件的结点插入到big结点之前。
注意:插入完成一个结点后,big结点要指向被新插入的结点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* partition(struct ListNode* head, int x){
if(head==NULL) return NULL;
struct ListNode* big,*small,*p,*dummy;
dummy=malloc(sizeof(struct ListNode));
dummy->next=head;
big=small=dummy;
while(big!=NULL && big->next!=NULL){
if(big->next->val<x)
big=big->next;
else
break;
}
small=big->next;
while(small!=NULL && small->next!=NULL){
if(small->next->val<x){
p=small->next;
small->next=p->next;
p->next=big->next;
big->next=p;
big=big->next;
}
else{
small=small->next;}
}
return dummy->next;
}
作者:。。。。
链接:https://leetcode.cn/problems/partition-list/solutions/2470828/fen-ge-lian-biao-shuang-zhi-zhen-jie-ti-e3p86/