把单链表按某值划分成左边小,中间相等,右边大的形式,时间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;
}
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;
}
相关文章推荐
- 链表问题---将单向链表按某值划分成左边小,中间相等,右边大的形式
- Java——将单向链表按某值划分成左边小、中间相等、右边大的形式(基础问题)
- 将单向链表按某个值划分成左边小、中间相等、右边大的形式 Python 版
- 将单向链表按某值划分成左边小、 中间相等、 右边大的形式~迎娶是挺
- [链表] - 将单向链表按某值划分成左边小、中间相等、右边大的形式
- 将单向链表按某值划分成左边小、中间相等、右边大的形式
- 将单向链表按某值划分成左边小、中间相等、右边大的形式
- Java——将单向链表按某值划分成左边小、中间相等、右边大的形式(进阶问题)
- 将单向链表按某值划分成左边小,中间相等,右边大
- C++链表划分左边小中间等右边大 时间复杂度O(n) 空间复杂度O(1)
- C++将链表划分为左边小,中间等,右边大于pivotKey的形式
- [JS]链表划分给定中间值,小的在左边,大的在右边并保持原排序
- 如何重新排列数组使得数组左边为奇数,右边为偶数,并使得空间复杂度为O(1),时间复杂度为O(n)
- 给定一个存放整数的数组,重新排列数组使得数组左边为奇数,右边为偶数。要求:空间复杂度O(1),时间复杂度为O(n)
- 划分一个整形数组,把负数放在左边,零放在中间,正数放在右边
- 百度笔试:给定一个存放整数的数组,重新排列数组使得数组左边为奇数,右边为偶数。 要求:空间复杂度O(1),时间复杂度为O(n)
- [JS]链表划分给定中间值,小的在左边,大的在右边并保持原排序
- 4.给定一个存放整数的数组,重新排列数组使得数组左边为奇数,右边为偶数。 要求:空间复杂度O(1),时间复杂度为O(n)
- 给定一个存放整数的数组,重新排列数组使得数组左边为奇数,右边为偶数。 要求:空间复杂度O(1),时间复杂度为O(n)。
- WinForm 窗口出现在靠屏幕左边中间或者右边中间