判断两个链表是否相交,若相交,求交点。(假设链表不带环)

判断是否相交

不带环链表有三种情况,V,Y,L型,而这三种情况相交的共同点是两条链表的最后一个结点是相同的,这就解释了为什么以最后一个结点作为判断依据。

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;
}

求交点

思路:求出两条链表结点的差值(gap);长链表先走完这个差值后,两条链表一起向后走,直到两个指针指向同一个结点,此时这个结点就是交点。

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;
		}
	}
	//求交点
	while (pCur1 != pCur2)
	{
		pCur1 = pCur1->next;
		pCur2 = pCur2->next;
	}
	return pCur1;
}

猜你喜欢

转载自blog.csdn.net/weixin_40995778/article/details/82825098