版权声明:本文自由转载,转载请注明出处。 https://blog.csdn.net/qq_38071429/article/details/83956399
图解:
代码:
public class Solution {
/*
遍历两条链表得到各自的长度,长的先next两条链表的长度差,然
后一起走next,如果有公共结点,此结点及之后的链表值都相同。
*/
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1==null||pHead2==null) return null;
ListNode pre1 = pHead1,pre2 = pHead2;
while(pre1!=null){
length1++;
pre1 = pre1.next;
}
while(pre2!=null){
length2++;
pre2 = pre2.next;
}
if(length1>=length2) {
for(int i=1;i<=length1-length2;i++){
pHead1 = pHead1.next;
}
}
else{
for(int i=1;i<=length2-length1;i++)
pHead2 = pHead2.next;
}
while(pHead1!=pHead2){
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
return pHead1;
}
}
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/