判断单链表是否有环路可以参考:单链表判断环路及环路的入口
typedef int DataType;//节点中数据类型
typedef struct ListNode//节点数据结构
{
DataType data;
struct ListNode *next;
} ListNode;
typedef struct CheckNoode/
{
int flag;
ListNode *p1;
ListNode *p2;
} CheckNoode;
1.判断两个链表是否相交,若相交,求交点。(假设不带环)
//判断是否相交
bool CheckIsMeet(ListNode *plist1,ListNode *plist2)
{
while (plist1->next != NULL)
{
plist1 = plist1->next;
}
while (plist2->next != NULL)
{
plist2 = plist2->next;
}
if (plist1 == plist2)
{
return true;
}
else
{
return false;
}
}
//若相交,求交点
ListNode *AnswerMeetNode(ListNode *plist1,ListNode *plist2){
int count1 = 0;
int count2 = 0;
int count = 0;
ListNode *cur1 = plist1;
ListNode *cur2 = plist2;
while (cur1 != NULL)
{
count1++;
cur1 = cur1->next;
}
while (cur2 != NULL)
{
count2++;
cur2 = cur2->next;
}
count = count1 - count2;
if (count > 0)
{
while (count--)
{
plist1 = plist1->next;
}
}
else
{
count = -count;
while (count--)
{
plist2 = plist2->next;
}
}
while (plist1 != plist2)
{
plist1 = plist1->next;
plist2 = plist2->next;
}
return plist1;
}
void Test1()
{
ListNode *plist1 = NULL;
ListNode *plist2 = NULL;
bool flag = true;
if (flag)
{
printf("相交!\n");
printf("交点为:%d\n",AnswerMeetNode(plist1,plist2)->data);
}
else
{
printf("不想交!\n");
}
}
2.判断两个链表是否相交,若相交,求交点。(假设可能带环)
1).两个都不带环
有可能相交,有可能不相交
2).一个带环一个不带环,必定不相交。
3).两个都带环
不相交
相交:交点不在环上;交点在环上
//判断两个链表是否相交,若相交,求交点.(假设链表可能带环)
CheckNoode CheckIsMeetTop(ListNode *plist1, ListNode *plist2)
{
ListNode *tmp1 = NULL;
ListNode *tmp2 = NULL;
CheckNoode ret = { 0, NULL, NULL };
tmp1 = IsCycle(plist1);
tmp2 = IsCycle(plist2);
if ((tmp1 == NULL) && (tmp2 == NULL))
{
//都不带环
tmp1 = plist1;
tmp2 = plist2;
while (tmp1->next != NULL)
{
tmp1 = tmp1->next;
}
while (tmp2->next != NULL)
{
tmp2 = tmp2->next;
}
if (tmp1 == tmp2)
{
//相交
ret.plist1 = AnswerMeetNode(plist1, plist2);
ret.flag = 1;
return ret;
}
else
{
//不相交
ret.flag = 1;
return ret;
}
}
else if ((tmp1 != NULL) && (tmp2 != NULL))
{
//两者都带环
ListNode *tmp = tmp1->next;
while ((tmp != tmp2) && (tmp != tmp1))
{
tmp = tmp->next;
}
if (tmp == tmp2)
{
//相交
tmp1 = GetCycleEnter(plist1,tmp1);
tmp2 = GetCycleEnter(plist2,tmp2);
if (tmp1 == tmp2)
{
//交点在链上
int count1 = 0;
int count2 = 0;
int count = 0;
ListNode *cur1 = plist1;
ListNode *cur2 = plist2;
while (cur1 != tmp1)
{
count1++;
cur1 = cur1->next;
}
while (cur2 != tmp1)
{
count2++;
cur2 = cur2->next;
}
count = count1 - count2;
if (count > 0)
{
while (count--)
{
plist1 = plist1->next;
}
}
else
{
count = -count;
while (count--)
{
plist2 = plist2->next;
}
}
while (plist1 != plist2)
{
plist1 = plist1->next;
plist2 = plist2->next;
}
ret.plist1 = plist1;
ret.flag = 3;
return ret;
}
else
{
//两个交点都在环上
ret.plist1 = tmp1;
ret.plist2 = tmp2;
ret.flag = 3;
return ret;
}
}
else
{
//不相交
ret.flag = 3;
return ret;
}
}
else
{
//一个带环,一个不带环。必不相交
ret.flag = 2;
return ret;
}
}