//思路:
//设 pHead1 的长度为 a + c,pHead2 的长度为 b + c,其中 c 为尾部公共部分长度,
//可知 (a + c) + b = (b + c) + a。
//当访问 pHead1 链表的指针访问到链表尾部时,令它从链表 pHead2 的头部开始访问链表 pHead2;
//同样地,当访问 pHead2 链表的指针访问到链表尾部时,令它从链表 pHead1 的头部开始访问链表 pHead1。
//这样就能控制访问 pHead1 和 pHead2 两个链表的指针能同时访问到交点。
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1==null || pHead2==null){
return null;
}
ListNode cur1 = pHead1;
ListNode cur2 = pHead2;
while (cur1!=cur2){
if(cur1==null){
cur1 = pHead2;
}else{
cur1 = cur1.next;
}
if(cur2==null){
cur2 = pHead1;
}else{
cur2 = cur2.next;
}
}
return cur1;
}
www.mianshi.online,www.i9code.cn
本文由博客一文多发平台 OpenWrite 发布!