https://leetcode.com/problems/partition-list/description/
https://discuss.leetcode.com/category/94/partition-list
来自@yeze322 的简洁解法
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
第一想法就是先找到第一个大于或等于3的元素的前一个first,然后继续遍历,若后续有小于3的元素,则插入到first后,在原链表上调整。
通过新增一个tempHead,使得能在head前插入。
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
if (!head) return head;
ListNode* tempHead = new ListNode(head->val);
tempHead->next = head;
ListNode* first = tempHead;
while (first->next != NULL && first->next->val < x) {
first = first->next;
}
ListNode* pre = first;
ListNode* next = first->next;
while (next != NULL) {
if (next->val < x) {
// 要把next插入到first后
// 先把pre指向next->next保证后续链表不断
pre->next = next->next;
// 然后独立出来的next,
// 将next指向first->next
// 保证next可以指向first后面的链表
next->next = first->next;
// 将first指向next完成插入
first->next = next;
// 重置next
next = pre->next;
// 重置first
first = first->next;
} else {
pre = next;
next = next->next;
}
}
return tempHead->next;
}
};
不过还有更简单的直接遍历,维护小于x的列表和大于x的列表,最后拼起来然后,是真的简洁…
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode left(0), right(0);
ListNode *l = &left, *r = &right;
while(head){
ListNode* & ref = head->val < x ? l : r;
ref->next = head;
ref = ref->next;
head = head->next;
}
l->next = right.next;
r->next = NULL;
return left.next;
}
};