码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-03-30 07:10:18      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:无环单链表相交

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

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


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

标签:无环单链表相交

原文地址:http://green906.blog.51cto.com/10697569/1758221

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!