求链表中环的入口

链表中没环就返回NULL

有就返回环的入口


三种基本思路:

1、快慢指针找到环内的一个node,然后从链表头开始,对于每一个node,看它在不在环中

2、用map存一下访问过的节点地址,看当前node的地址是否在map中

3、其实,经过计算,对于1中,快慢指针相遇的地方,再开始以慢指针开始走,

另一方面,在链表的头部也用一个慢指针开始走,二者相遇的地方便是环的入口

(代码并未进行运行验证)


typedef struct node
{
	int data;
	struct node * next;
}listNode;


//find the first node in the cycle
//1.step into the circle first and then for every node, take a loop to make sure
//2.store the previous node and compare with the cunrrent node (what structure to store?)
//3.after computation,while using slow and fast pointer,
// we can get that a slow pointer at the begining and another one 
// at the encounter position will meet at the entrance of the cycle 
listNode *findFirstNodeInCycle1(listNode *pHead)
{
	listNode *pFast=pHead;
	listNode *pSlow=pHead;

	while(pFast!=NULL&&pFast->next!=NULL)
	{
		pFast=pFast->next->next;
		pSlow=pSlow->next;
		if(pSlow==pFast)
			break;
	}

	if(pFast==NULL||pFast->next==NULL)
		return NULL;

	//now the nodes are in the loop
	//begin with the head
	while(pHead)
	{
		
		pSlow=pSlow->next;
		while(pSlow)
		{
			if(pSlow==pHead)
				return pHead;
			if(pSlow==pFast)
				break;		
			pSlow=pSlow->next;
		}
		pHead=pHead->next;
	}
}

//store in a map? good or not?
listNode *findFirstNodeInCycle2(listNode *pHead)
{
	if(pHead==NULL)
		return;
	listNode *temp=pHead-next;
	
	map<int,char> storeMap;
	map[int(pHead)]=' ';

	while(teamp!=NULL&&storeMap.find(temp)==storeMap.end())
	{
		storeMap[int(temp)]=' ';
		temp=temp->next;
	}

	return temp;
}

listNode *findFirstNodeInCycle3(listNode *pHead)
{
	listNode *pFast=pHead;
	listNode *pSlow=pHead;

	while(pFast!=NULL&&pFast->next!=NULL)
	{
		pFast=pFast->next->next;
		pSlow=pSlow->next;

		if(pFast==pSlow)
		{
			listNode *pSlow2=pHead;
			while(pSlow2!=pSlow)
			{
				pSLow=pSlow->next;
				pSlow2=pSlow2->next;
			}
			return pSlow;
		}
	}
	return NULL;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值