单链表划分值区域

题目:将单向链表按某值划分称左边小,中间相等,右边大的形式

给定一个单链表的头节点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);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值