问题分析:
这道题的做法是遍历链表,发现比该数小的数使用尾插法插入一个链表,大的数再插入一个链表,最后再把两个链表连接在一起并且把最后一个结点的next置为空。
public static Node partition(Node head,int x)
{
Node small=null;
Node big=null;
Node smallLast=null;
Node bigLast=null;
Node cur=head;
while(cur!=null)
{
if(cur.val<x)
{
Node next =cur.next;
if(small==null)
{
small=cur;
}else{
smallLast.next=cur;
}
smallLast=cur;
cur=next;
}else{
Node next =cur.next;
if(big==null)
{
big=cur;
}else{
bigLast.next=cur;
}
bigLast=cur;
cur=next;
}
}
if(small==null)
{
return big;
}else{
smallLast.next=big;
if(bigLast!=null)
{
bigLast.next=null;
}
return small;
}
}