/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class Partition {
  public:
    ListNode* partition(ListNode* pHead, int x) {
        ListNode* gGuard, *gTail, *lGuard, *lTail;
        gGuard = gTail = (ListNode*)malloc(sizeof(ListNode));
        lGuard = lTail = (ListNode*)malloc(sizeof(ListNode));
        gGuard->next=gTail->next=lGuard->next=lTail->next=nullptr;
        ListNode* cur = pHead;
        while (cur) 
        {
            if (cur->val < x) 
            {
                lTail->next = cur;
                lTail = lTail->next;
            }else 
            {
                gTail->next = cur;
                gTail = gTail->next;
            }
            cur = cur->next;
        }
        gTail->next=nullptr;
        lTail->next = gGuard->next;
        pHead=lGuard->next;
        //free(gGuard);
        //free(lGuard);
        return pHead;
    }
};