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.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *partition(ListNode *head, int x) {
ListNode small_dummy(-1);
ListNode big_dummy(-1);
auto small_cur = &small_dummy;
auto big_cur = &big_dummy;
for (auto p = head; p; p = p->next) {
if (p->val < x) {
small_cur->next = p;
small_cur = p;
} else {
big_cur->next = p;
big_cur = p;
}
}
small_cur->next = big_dummy.next;
big_cur->next = NULL;
return small_dummy.next;
}
};
本文详细阐述了如何通过链表节点值将链表分为两部分,一部分包含小于给定值x的所有节点,另一部分包含大于等于x的所有节点,同时保持原始相对顺序不变。
2463

被折叠的 条评论
为什么被折叠?



