(1)先令cur=head,把链表分成两段,第一段为小于目标值得,第二段为大于等于目标值的
(2)让cur遍历链表并判断节点放入哪一段里,直到cur==null;
(3)若cur.val<x,把cur尾插法到第一段里(分为是否第一次,如是第一次放进去就行了),若cur.val>=x,一样的方法
(4)循环结束后把第二段尾插到第一段最后就行了,返回bs
(5)最后要判断所有节点都在某一段的情况,若都在第二段,头结点就应是as
(6)在判断若第二段有节点,则要把第二段ae.next设为null,防止链表成环
public class Partition {
public ListNode partition(ListNode pHead, int x) {
ListNode cur = pHead;
ListNode bs = null;
ListNode be = null;
ListNode as = null;
ListNode ae = null;
while(cur != null){
if(cur.val < x){
if(bs == null){
bs = cur;
be = cur;
}else{
be.next = cur;
be = be.next;
}
}else{
if(as == null){
as = cur;
ae = cur;
}else{
ae.next = cur;
ae = ae.next;
}
}
cur = cur.next;
}
if(bs == null){
return as;
}
be.next = as;
if(as != null){
ae.next = null;
}
return bs;
}
} 


京公网安备 11010502036488号