/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
#include <cstdlib>
class Partition {
public:
    ListNode* partition(ListNode* pHead, int x) {
        ListNode *cur = pHead;
        ListNode *lessHead, *lessTail, *greaterHead, *greaterTail;
        lessHead = lessTail = (ListNode*)malloc(sizeof(ListNode));
        greaterHead = greaterTail = (ListNode*)malloc(sizeof(ListNode));

        while(cur)
        {
            if(cur->val < x)
            {
                lessTail->next = cur;
                lessTail = lessTail->next;
            }
            else 
            {
                greaterTail->next = cur;
                greaterTail = greaterTail->next;
            }
            cur = cur->next;
        }

        lessTail->next = greaterHead->next;
        greaterTail->next = nullptr;

        return lessHead->next;
    }
};