给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
使用双指针的方式,各自构造一个大元素的头节点和小元素的头节点,同时遍历当前链表完善大小链表,最终将两个大小链表链接起来即可
ListNode* partition(ListNode* head, int x) {
if (head == NULL) return NULL;
ListNode small(0);
ListNode big(0);
ListNode *pre_small = &small;
ListNode *pre_big = &big;
while(head) {
if (head -> val < x) {
pre_small -> next = head;
pre_small = head;
} else {
pre_big -> next = head;
pre_big = head;
}
head = head -> next;
}
pre_small -> next = big.next;
pre_big -> next = NULL;
return small.next;
}