题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
方法一:两个指针以同样速度走完相同长度路径必会相遇
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){
//1走完就去走2
cur1 = pHead2;
}else{
//只有非空时才能往下一个位置移动!
cur1 = cur1.next;
}
if(cur2==null){
//2走完转而走1
cur2 = pHead1;
}else{
cur2 = cur2.next;
}
}
return cur1;
}
方法二:双层循环,遍历搜索
嵌套循环,时间复杂度
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
//两链表同时搜索,两个活动指针
ListNode cur1 = pHead1;
ListNode cur2 = pHead2;
while(cur1!=null){
//这一步非常重要,保证每次循环开始,指向头结点
cur2 = pHead2;
while(cur2!=null){
if(cur1==cur2)return cur2;
cur2 = cur2.next;
}
cur1 = cur1.next;
}
//若没有匹配结果,返回{}
return null;
}
#剑指offer#