/**
* 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
// 创建两个 dummy 节点,分别保存小于 x 的节点和 大于等于 x 的节点
ListNode lessHead(0), greaterHead(0);
ListNode *lsPtr = &lessHead, *gtPtr = &greaterHead;
while (head != nullptr) {
if (head->val < x) {
lsPtr->next = head;
lsPtr = lsPtr->next;
} else {
gtPtr->next = head;
gtPtr = gtPtr->next;
}
head = head->next;
}
// 分完了再连起来
lsPtr->next = greaterHead.next;
gtPtr->next = nullptr; // 防止成环
return lessHead.next;
}
};