题解 | #划分链表#
划分链表
https://www.nowcoder.com/practice/1dc1036be38f45f19000e48abe00b12f
/** * 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) { auto *p=new ListNode(-1); auto *p_cpy=p; auto *q=new ListNode(-1); auto *q_cpy=q; while(head!=nullptr) { if(head->val<x) { p_cpy->next=head; p_cpy=p_cpy->next; } else { q_cpy->next=head; q_cpy=q_cpy->next; } head=head->next; } p_cpy->next=q->next; q_cpy->next=nullptr; return p->next; } };