思想: 如果它们相交,则最后一个节点一定是共有的。
ListNode* IsIntersect(ListNode * list1, ListNode* list2 )
{
assert(list1 && list2);
ListNode* l1 = list1 ;
ListNode* l2 = list2 ;
int cout1 = 0;
int cout2 = 0;
while(l1->_next == NULL )
{
l1 = l1->_next;
++cout1;
}
while(l2->_next == NULL )
{
l2 = l2->_next;
++cout2;
}
if(l1 != l2)
return NULL ;
l1 = list1;
l2 = list2;
int length = 0;
if(cout1 > cout2)
{
length = cout1 - cout2;
}
else
{
length = cout2 - cout1;
}
while(length--)
{
if(cout1 > cout2)
l1 = l1->_next;
else
l2 = l2->_next;
}
while(11)
{
if(l1 == l2)
return l1;
else
{
l1 = l1->_next;
l2 = l2->_next;
}
}
return NULL ;
}
转载于:https://blog.51cto.com/green906/1758221