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.
直接使用二级指针即可,解法如下:
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode* less = NULL;
ListNode** less_pp = &less;
ListNode* not_less = NULL;
ListNode** not_less_pp = ¬_less;
while(head != NULL){
if(head->val < x){
*less_pp = head;
less_pp = &(head->next);
}
else{
*not_less_pp = head;
not_less_pp = &(head->next);
}
head = head->next;
}
if(less != NULL){
*less_pp = not_less;
*not_less_pp = NULL; //注意我们需要把not_less分支最后一各节点赋空,负责会死循环
}
else
less = not_less;
return less;
}
};
本文介绍了一种链表分区算法,该算法将链表中小于给定值x的节点置于大于等于x的节点之前,同时保持原有相对顺序不变。示例中给出1->4->3->2->5->2,在x=3的情况下返回1->2->2->4->3->5。通过使用二级指针实现这一目标。
1708

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



