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.
For example,
Given 1->4->3->2->5->2
and   x = 3,
return< Span class= "Apple-converted-space" > 1->2->2->4->3->5
.
One idea is to find a node first, the value of the node is less than X and the node's next node value is greater than or equal to X, so that the two nodes are recorded as S and L, and then from L began to traverse the linked list, the value less than X is inserted between S and L, and update s,l does not change. The idea worth noting is that the first, the head node value is greater than X, then S is null, all nodes smaller than x are inserted into the head before the first one needs to be updated, and then S is not null; the second noteworthy is the need to update s after each insertion of SL, Otherwise, an error occurs. The AC code is as follows:
listnode* partition (listnode* head,intx) {if(!head)returnHead; //Find NodesListNode * s=Head; ListNode* l=NULL; if(Head->val >=x) {L=Head; S=NULL; } Else { while(S->next!=null && S->next->val <x) s=s->Next; if(S->next = =NULL)returnHead; L=s->Next; } //search node less than x from node LListNode *fir=l; ListNode*sec=fir->Next; for(; sec!=NULL;) { if(Fir->val>=x && Sec->val <x) {fir->next = sec->Next; if(s) {s->next =sec; SEC->next =l; S=sec; } Else{sec->next =l; Head=sec; S=sec; } sec= fir->Next; } Else{fir= fir->Next; SEC= sec->Next; } } returnHead; }
Leetcode "86" Partition List