判断两个单链表是否相交?若相交求交点

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了判断两个单链表是否相交?若相交求交点相关的知识,希望对你有一定的参考价值。

 思想: 如果它们相交,则最后一个节点一定是共有的。

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


以上是关于判断两个单链表是否相交?若相交求交点的主要内容,如果未能解决你的问题,请参考以下文章

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

POJ 1127 Jack Straws ( 求直线交点, 判断线段是否相交(含端点) )

判断两个单链表是否相交及相交的第一个节点

1.11判断两个无环单链表是否相交

C++相交链表

9.判断两个单链表是否相交