classSolution{public:ListNode*partition(ListNode*head,intx){if(head==NULL||head->next==NULL)returnhead;ListNode*beforenode;ListNode*minnode,*maxnode;// find the 1st minnode
if(head->val<x){minnode=head;}else{beforenode=head;minnode=head->next;while(minnode!=NULL&&minnode->val>=x){beforenode=minnode;minnode=minnode->next;}if(minnode==NULL)returnhead;beforenode->next=minnode->next;minnode->next=head;// now the head is minnode;
}beforenode=minnode;maxnode=minnode->next;while(maxnode!=NULL&&maxnode->val<x){beforenode=maxnode;maxnode=maxnode->next;}if(maxnode==NULL||maxnode->next==NULL)returnminnode;// now find minnode and maxnode. the head is minnode
head=minnode;ListNode*now=maxnode->next;while(now!=NULL){if(now->val>=x){maxnode=now;now=now->next;}else{ListNode*tmp=beforenode->next;maxnode->next=now->next;beforenode->next=now;now->next=tmp;now=maxnode->next;beforenode=beforenode->next;}}returnhead;}};