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.
For example,
Given 1->4->3->2->5->2
and x = 3,
return 1->2->2->4->3->5
.
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* partition(ListNode* head, int x) { 12 13 if(head==NULL||head->next==NULL) 14 return head; 15 ListNode *p,*pre,*post,*temp,*dummy=new ListNode(0); 16 int max,flag=1; 17 dummy->next=head;pre=dummy; 18 p=dummy;max=p->val; 19 while(p->next!=NULL) 20 { 21 if(flag&&p->next->val>=x) 22 { 23 pre=p; 24 flag=0; 25 } 26 else if(!flag&&p->next->val<x) 27 { 28 post=p->next->next; 29 temp=pre->next; 30 pre->next=p->next; 31 pre=p->next; 32 pre->next=temp; 33 p->next=post; 34 p=pre; 35 36 } 37 p=p->next; 38 if(p==NULL) 39 break; 40 } 41 return dummy->next; 42 43 } 44 };