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
.
class Solution {
public:
ListNode *partition(ListNode *head, int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode *H1=new ListNode(0);
H1->next=head;
ListNode *p , *q , *cur;
for( p=H1 ; p->next && p->next->val<x ; p=p->next);
ListNode *H2=new ListNode(0);
H2->next=p->next;
for(q=H2 ; q->next ;){
if(q->next->val<x){
cur=q->next;
q->next=q->next->next;
p->next=cur;
p=cur;
continue;
}
q=q->next;
}
p->next=H2->next;
delete H2;
p=H1->next;
delete H1;
return p;
}
};