1. 程式人生 > >判斷單鏈表是否帶環?若帶環,求環的長度,求環的入口點

判斷單鏈表是否帶環?若帶環,求環的長度,求環的入口點

判斷是否帶環,若帶環返回相遇點,否則返回空

pNode IsCircle(pList plist)
{
	pNode pFast = plist;
	pNode pSlow = plist;
	while (pFast && pFast->next)
	{
		pFast = pFast->next->next;
		pSlow = pSlow->next;
		if (pFast == pSlow)
		{
			return pFast;
		}
	}
	return NULL;
}

求環的長度

int GetCircleLen(pList plist)
{
	//1.判斷是否帶環
	pNode pMeetNode = IsCircle(plist);
	pNode pCur = pMeetNode;
	int count = 1;//這裡count不能為0
	if (pMeetNode == NULL)//如果不帶環,則環的長度為0
	{
		return 0;
	}
	//2.程式走到這裡說明一定帶環,用遍歷的方法求環的長度
	while (pCur->next != pMeetNode)
	{
		count++;
		pCur = pCur->next;
	}
	return count;
}

 求環的入口點

pNode GetEnterNode(pList plist, pNode pMeetNode)
{
	pNode pH = plist;//pH從連結串列頭開始走
	pNode pM = pMeetNode;//pM從相遇點開始走
	if (plist == NULL || pMeetNode == NULL)
	{
		return NULL;
	}
	while (pH != pM)
	{
		pH = pH->next;
		pM = pM->next;
	}
	return pH;
}