/** * 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* partition(ListNode* head, int x) { // write code here ListNode small(0), big(0); ListNode* p1 = &small, *p2 = &big; while (head) { if (head->val < x) { p1->next = head; p1 = p1->next; } else { p2->next = head; p2 = p2->next; } head = head->next; } p2->next = nullptr; // 断开尾部 p1->next = big.next; // 拼接 return small.next; } };