https://leetcode-cn.com/problems/partition-list/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* partition(struct ListNode* head, int x){
if (NULL == head) return head;
struct ListNode result;
struct ListNode *node = &result;
node->next = head;
struct ListNode *pre = NULL;
struct ListNode *insert_pre = node;
struct ListNode *inser_node = NULL; // 找到的第一个大于等于val的值
struct ListNode *next = NULL;
bool find = false;
while (head) {
if (find == false) {
if (head->val < x) {
//当前遍历的节点val都小于x, 直接转到下一个即可
insert_pre = head;
head = head->next;
} else {
// 当前遍历的节点的值大于等于x, 那么后续遍历到的小于x的节点都需要挪到这个节点之前
inser_node = head;
pre = head;
head = head->next;
find = true;
}
} else {
if (head->val >= x) {
pre = head;
head = head->next;
} else {
// 需要把当前的节点挪到第一个大于x的节点之前
next = head->next; //记录当前节点的下一个节点
//插入到第一个大于x的节点之前 inser_node 之前
insert_pre->next = head;
head->next = inser_node;
insert_pre = insert_pre->next;
pre->next = next;
head = next;
}
}
}
return result.next;
}