题解 | 两个链表的第一个公共结点
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode ph1 = pHead1;
ListNode ph2 = pHead2;
int l1 = 0;
int l2 = 0;
while(ph1 != null){
ph1 = ph1.next;
l1++;
}
while(ph2 != null){
ph2 = ph2.next;
l2++;
}
if(l1 == l2){
while(pHead1 != pHead2){
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
return pHead1;
}
else if(l1>l2){
int l= l1-l2;
while(l-->0){
pHead1 = pHead1.next;
}
while(pHead1 != pHead2){
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
return pHead1;
}
else{
int l= l2-l1;
while(l-->0){
pHead2 = pHead2.next;
}
while(pHead1 != pHead2){
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
return pHead1;
}
}
}
常规思路求解,得出长度差然后先走长度差个节点 之后就一起走
