题解 | #链表分割#
链表分割
http://www.nowcoder.com/practice/0e27e0b064de4eacac178676ef9c9d70
import java.util.*;
public class Partition {
public ListNode partition(ListNode head, int x) {
//根据x,将链表中的数据划分成两部分
//小于x的部分
ListNode bs=null;
ListNode be=null;
//大于x的部分
ListNode as=null;
ListNode ae=null;
while(head!=null){
//判断当前head的val是哪一部分
if(head.val<x){
//判断是否是第一次插入
if(bs==null){
bs=head;
be=head;
}else{
be.next=head;
be=be.next;
}
head=head.next;
}else{
if(as==null){
as=head;
ae=head;
}else{
ae.next=head;
ae=ae.next;
}
head=head.next;
}
}
//链表数据全部大于x
if(bs==null){
return as;
}
if(as!=null){
ae.next=null;
}
be.next=as;
return bs;
}
}