Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal tox.
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
.
So Many pointers!!!
ListNode *partition(ListNode *head, int x){
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(!head) return head;
ListNode* p = NULL;
ListNode* pre = head;
ListNode* tmp = head;
if(head->val < x)
p = head;
else{
tmp = tmp ->next;
while(tmp)
if(tmp->val >= x){ pre = tmp; tmp = tmp->next;}
else break;
if(!tmp)return head;
else{
pre->next = tmp->next;
tmp->next = head;
head = tmp;
p = tmp;
}
}
tmp = pre->next;
while(tmp)
{
if(tmp->val < x)
{
if(p->next == tmp){
pre = tmp;
tmp = tmp->next;
p = p->next;
}else{
pre->next = tmp->next;
tmp->next = p->next;
p->next = tmp;
p = p->next;
tmp = pre->next;
}
}else{
pre = tmp;
tmp = tmp->next;
}
}
return head;
}