1. 程式人生 > >判斷兩個連結串列是否相交,若相交,求交點。(假設連結串列不帶環)

判斷兩個連結串列是否相交,若相交,求交點。(假設連結串列不帶環)

判斷是否相交

int IsCrossWithoutCircle(pList plist1, pList plist2)
{
	pNode pTail1 = plist1;
	pNode pTail2 = plist2;
	if (pTail1 == NULL || pTail2 == NULL)
	{
		return 0;
	}
	while (pTail1)
	{
		pTail1 = pTail1->next;
	}
	while (pTail2)
	{
		pTail2 = pTail2->next;
	}
	return pTail1 == pTail2;
}

求焦點

pNode GetCrossNode(pList plist1, pList plist2)
{
	int size1 = 0;
	int size2 = 0;
	pNode pCur1 = plist1, pCur2 = plist2;
	if (!IsCrossWithoutCircle(plist1, plist2))//先判斷兩連結串列是否相交
	{
		return NULL;
	}
	//求兩個連結串列中結點的個數
	while (pCur1)
	{
		size1++;
		pCur1 = pCur1->next;
	}
	while (pCur2)
	{
		size2++;
		pCur2 = pCur2->next;
	}
	//讓長的連結串列先朝後走差值步
	int gap = size1 - size2;
	pCur1 = plist1;
	pCur2 = plist2;
	if (gap > 0)
	{
		while (gap--)
		{
			pCur1 = pCur1->next;
		}
	}
	else
	{
		//此時gap為負數或0,所以++
		while (gap++)
		{
			pCur2 = pCur2->next;
		}
	}
	//求交點(v,y,同一條連結串列)
	while (pCur1 != pCur2)
	{
		pCur1 = pCur1->next;
		pCur2 = pCur2->next;
	}
	return pCur1;
}