
method 1: 使用两个空头结点记录
ListNode* partition(ListNode* head, int x) {
ListNode*before_head=new ListNode(0);
ListNode*before=before_head;
ListNode*after_head=new ListNode(0);
ListNode*after=after_head;
while(head){
if(head->val<x){
before->next=head;
before=before->next;
}
else{
after->next=head;
after=after->next;
}
head=head->next;
}
after->next=NULL;
before->next=after_head->next;
return before_head->next;
}
method 2:硬刚(蠢)
ListNode* partition(ListNode* head, int x) {
if(!head)return head;
ListNode*pre1=NULL;
if(head->val<x)pre1=head;
ListNode*pre2=head;
ListNode*temp=NULL;
while(pre2->next&&pre2->val<x){
pre1=pre2;
pre2=pre2->next;
}
while(pre2->next){
if(!pre2->next->next&&pre2->next->val<x){
if(pre1){
temp=pre2->next;
pre2->next=NULL;
temp->next=pre1->next;
pre1->next=temp;
}
else{
temp=head;
head=pre2->next;
pre2->next=NULL;
head->next=temp;
}
return head;
}
if(pre2->next->val<x){
if(pre1){
temp=pre2->next;
pre2->next=pre2->next->next;
temp->next=pre1->next;
pre1->next=temp;
pre1=pre1->next;
}
else{
temp=head;
head=pre2->next;
pre2->next=pre2->next->next;
head->next=temp;
pre1=head;
}
}
else
pre2=pre2->next;
}
return head;
}

426

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



