C++ | Separate 0 list and 1 list and append 1 list to 0 list


#1
ListNode* Solution::solve(ListNode* A) {
    if(not A)   return A;
    ListNode *head = A, *oneHead = nullptr, *zeroHead = nullptr;
    ListNode *ptr1 = nullptr, *ptr2 = nullptr;
    while(head) {
        ListNode *nextNode = head->next;
        if(head->val) {
            if(nullptr == oneHead) {
                oneHead = head;
                ptr1 = oneHead;
            }
            else {
                ptr1->next = head;
                ptr1 = ptr1->next;
            }
            if(ptr1)    ptr1->next = nullptr;
        }
        else {
            if(nullptr == zeroHead) {
                zeroHead = head;
                ptr2 = zeroHead;
            }
            else {
                ptr2->next = head;
                ptr2 = ptr2->next;
            }
            if(ptr2)    ptr2->next = nullptr;
        }
        head = nextNode;
    }
    if(zeroHead)    ptr2->next = oneHead;
    return zeroHead ? zeroHead : oneHead;
}