https://leetcode.com/problems/partition-list/
创建两个dummy node:leftDummy和rightDummy,分别对应划分后的两个链表。然后遍历原始链表,比给定的值小就连到leftDummy链表后面,否则就连到rightDummy链表后面。最后将两个链表连起来,注意将尾节点的next域置空。
Time complexity: O(n)
Space complexity: O(1)
C++
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
if (!head || !head->next) return head;
ListNode left_dummy(0), right_dummy(0);
ListNode *l = &left_dummy, *r = &right_dummy;
while (head) {
if (head->val < x) {
l->next = head;
l = l->next;
} else {
r->next = head;
r = r->next;
}
head = head->next;
}
l->next = right_dummy.next;
r->next = NULL;
return left_dummy.next;
}
};