将小于x的节点存入low链表中,将大于等于x的节点存入high链表中,并且分别统计小于和大于等于x的节点的数目,用于判断连接链表的方式,然后将两个链表连接起来便可以得到结果。

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution { 
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @param x int整型 
     * @return ListNode类
     */
    ListNode* cow_partition(ListNode* head, int x) {
        // write code here
        if(head == nullptr) {
            return head;
        }
        int count = 0;
        int count_low = 0;
        int count_high = 0;
        auto list_low = new ListNode(0);
        ListNode* low_node = list_low;
        auto list_high = new ListNode(0);
        ListNode* high_node = list_high;
        ListNode* cur_node = head;
        while(cur_node != nullptr) {
            if(cur_node->val < x) {
                low_node->next = cur_node;
                count_low++;
                low_node = low_node->next;
            } else {
                high_node->next = cur_node;
                count_high++;
                high_node = high_node->next;
            }
            cur_node = cur_node->next;
        }
        high_node->next = nullptr;
        if(count_low == 0) {
            head = list_high->next;
            return head;
        } else if(count_high == 0) {
            head = list_low->next;
            return head;
        }
        cur_node = list_low;
        while(cur_node != nullptr) {
            cur_node = cur_node->next;
            count++;
            if(count == count_low) {
                cur_node->next = list_high->next;
                break;
            }
        }
        head = list_low->next;
        return head;
    }
};