题目:将单向链表按某值划分称左边小,中间相等,右边大的形式
给定一个单链表的头节点head,节点的值类型是整型,再给定一个整数pivot,实现一个调整链表的函数,将链表调整为左部分小于pivot的节点,中间部分等于pivot的节点,右部分都是大于pivot的节点
数组解法:
Node listpartition1(Node head,int pivot)
{
if(head==null)
{
return head;
}
Node cur=head;
int i=0;
while(cur!=null)
{
i++;
cur=cur->next;
}
Node nodearr[]=new Node[i];
i=0;
cur=head;
for(int i=0;i!=nodearr.length;i++)
{
nodearr[i]=cur;
cur=cur->next;
}
arrpartition(nodearr,pivot);
for(int i=0;i!=nodearr.length;i++)
{
nodearr[i-1]->next=nodearr[i];
}
nodearr[i-1]->next=null;
return nodearr[0];
}
进阶指针解法
Node listpartition2(node head,int pivot)
{
node sh=null;
node st=null;
node eh=null;
node et=null;
node mh=null;
node mt=null;
node next=null;
while(head!=null)
{
next=head->next;//保存下一个值
head->next=null;
if(head->value<pivot)
{
if(sh==null)
{
sh=head;
st=head;
}
else
{
st->next=head;
st=head;
}
}
else if(head->value==pivot)
{
if(eh==null)
{
eh=head;
et=head;
}
else
{
et->next=head;
et=head;
}
}
else
{
if(mh==null)
{
mh=head;
mt=head;
}
else
{
mt->next=head;
mt=head;
}
}
head=next;//向下遍历
}
if(st!=null)//如果有小于区域
{
st->next=eh;
et=et==null?st:et;//下一步,谁去连大于区域的头,谁就变成et
}
if(et!=null)//如果有等于区域
{
et->next=mh;
}
return sh!=null?sh:(eh!=null?eh:mh);
}