Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example:
Input: head = 1->4->3->2->5->2, x = 3 Output: 1->2->2->4->3->5
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* partition(struct ListNode* head, int x) {
if(head==NULL||head->next==NULL)
return head;
int flag=0;
struct ListNode *cur,*pre,*p,*q,*hhead;
pre=(struct ListNode *)malloc(sizeof(struct ListNode));
hhead=(struct ListNode *)malloc(sizeof(struct ListNode));
if(head->valnext=head;
flag=1;
}
pre->next=head;
cur=head;
while(cur!=NULL)
{
if(cur->val>=x)
break;
cur=cur->next;
pre=pre->next;
}
if(cur==NULL)
return head;
q=cur;
cur=cur->next;
while(cur!=NULL)
{
if(cur->valnext=cur;
flag=1;
}
p=cur->next;
cur->next=pre->next;
pre->next=cur;
q->next=p;
pre=pre->next;
cur=p;
continue;
}
q=q->next;
cur=cur->next;
}
if(flag==0)
hhead->next=head;
return hhead->next;
}