您的位置:首页 > 其它

把单链表按某值划分成左边小,中间相等,右边大的形式,时间O(n),空间O(1)

2017-12-04 16:36 309 查看
public static Node partation(Node list,int k){
Node head=list;
Node sf=null,se=null;//小的头,尾
Node ef=null,ee=null;//相等的头,尾
Node bf=null,be=null;//大的头,尾
while(head!=null){
Node next=head.next;//把头结点拿下来
head.next=null;
if(head.val<k){
//小于
if(sf==null){
sf=head;
se=head;
}else{
se.next=head;
se=head;
}
}else if(head.val==k){//等于
if(ef==null){
ef=head;
ee=head;
}else{
ee.next=head;
ee=head;
}
}else{
//大于
if(bf==null){
bf=head;
be=head;
}else{
be.next=head;
be=head;
}
}
head=next;
}
if(se!=null){
//小的尾结点不空
se.next=ef;
ee=ee==null?se:ee;
}
if(ee!=null){
//相等的尾结点不空
ee.next=bf;
}
return sf!=null?sf:ef!=null?ef:bf;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐