Partition is a quick preparation task. It is used in many other problems, such as finding a number that meets a certain condition.
In an array, you can replace one or more pointers at one end in sequence, which does not guarantee the relative order in the source array. It is different in the linked list. You cannot get the pointer at the end. You can only find the first node that does not meet the partition condition, that is, a large number, and then find a smaller number, move the decimal node to the front, so there is a difference with the array approach. The partition of the linked list only has one pointer to actually move, and the other pointer keeps the insert position.
class Solution {public: ListNode *partition(ListNode *head, int x) { if(!head || !head->next) return head; ListNode *left = head, *right = head, *pre1 = NULL, *pre2 = NULL; while(left&&left->val<x){ pre1 = left; left = left->next; } right = left; while(right){ while(right&&right->val>=x){ pre2 = right; right = right->next; } if(right != left&&right){ pre2->next = right->next; if(pre1 == NULL){ right->next = head; head = right; }else{ right->next = pre1->next; pre1->next = right; } pre1 = right; right = pre2->next; } } return head; }};