单链表的实现:https://blog.csdn.net/weixin_41892460/article/details/82855823
1.假设链表不带环
思路:两个不带环的链表相交,则最后一个结点一定相同。
int CheckCross(pList list1, pList list2)
{
if (NULL == list1 || NULL == list2)
return 0;
//遍历到最后一个节点
while (list1->next)
{
list1 = list1->next;
}
while (list2->next)
{
list2 = list2->next;
}
if (list1 == list2)
{
return 1;
}
else
{
return 0;
}
**思路:利用快慢指针,首先求出两个链表的长度差n-1,然后让长的链表先走n-1步。然后一起走,相同的地方就是交点。**
pNode GetCrossNode(pNode list1, pList list2)
{
if (NULL == list1 || NULL == list2)
return 0;
int size1 = 0;
int size2 = 0;
int del = 0;
pNode cur1 = list1;
pNode cur2 = list2;
while (cur1)
{
cur1 = cur1->next;
size1++;
}
while (cur2)
{
cur2 = cur2->next;
size2++;
}
del = size1 - size2;
cur1 = list1;
cur2 = list2;
if (del > 0)
{
while (del--)
{
cur1 = cur1->next;
}
}
else
{
while (del++)
{
cur2 = cur2->next;
}
}
while (cur1 != cur2)
{
cur1 = cur1->next;
cur2 = cur2->next;
}
return cur1;
}
2.假设单链表带环
pNode GetCrossNodeH(pNode list1, pList list2)
{
pNode fast = list1;
pNode slow = list2;
if (NULL == list1 || NULL == list2)
return 0;
while (fast&&fast->next)
{
fast = fast->next->next;
slow = slow->next;
if (slow == fast)
return slow;
}
return NULL;
}