/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *partition(ListNode *head, int x) {
if (!head || !head->next) return head;
ListNode *lh = NULL, *lc = NULL, *gh = NULL, *gc = NULL;
while (head) {
if (head->val < x) {
if(!lh) {
lh = lc = head;
} else {
lc->next = head;
lc = lc->next;
}
} else {
if (!gh) {
gh = gc = head;
} else {
gc->next = head;
gc = gc->next;
}
}
head = head->next;
}
if(gc) {
gc->next = NULL;
}
if (lc) {
lc->next = gh;
} else {
lh = gh;
}
return lh;
}
};