假设两个链表的头指针分别为h1,h2
-
思路一
将h1的尾节点的指针域指向h2的头结点,即将h2连接在h1的后面。如果两个链表相交,那么此时的h2肯定是个循环链表,否则还是一个单向链表。此时的问题就简化成判断此时的h2是否为循环链表。
代码实现
bool isIntersect(pNode h1, pNode h2)
{
if(!h1 || !h2)
return false;
bool flag = false;
pNode temp_h1 = h1;
pNode temp_h2 = h2;
//找到第一个链表的尾节点,将第二个链表挂在其后
while(temp_h1->next != NULL)
temp_h1 = temp_h1->next;
temp_h1->next = h2;
do
{
temp_h2 = temp_h2->next;
}while(temp_h2 && temp_h2 != h2);
if(temp_h2 == h2)
flag = true;
//将链表恢复原样
temp_h1->next = NULL;
return flag;
}
-
思路二
如果两个单向链表相交,那么这两个链表的尾结点一定相同(地址相同)。
代码实现
bool isIntersect(pNode h1, pNode h2)
{
if(!h1 || !h2)
return false;
pNode tail_h1 = h1;
pNode tail_h2 = h2;
while(tail_h1->next != NULL)
tail_h1 = tail_h1->next;
while(tail_h2->next != NULL)
tail_h2 = tail_h2->next;
if(tail_h1 == tail_h2)
return true;
return false;
}
参考书籍:《编程之美》