给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
思路:把小于 x 的节
点和大于等于x的节点分别存成两段,再拼到一起去。
class Solution { public: ListNode* partition(ListNode* head, int x) { if (!head) return nullptr; ListNode *head1 =new ListNode(0),*p=head1, *head2 = new ListNode(0), *q=head2; while (head){ if (head->val < x){//前半段,头节点head1, p不断移动 p->next = head; p = p->next; } else{//前半段,头节点head2, q不断移动 q->next = head; q = q->next; } head = head->next; } //两半段拼接起来 p->next = head2->next; q->next = nullptr; return head1->next; } };