【剑指offer】链表第一个公共子结点

时间:2023-03-08 17:28:06

*思路: 先求得两个链表的长度,然后得到长度差diff,再先遍历长链表diff步后,再同时遍历两个链表并比较对象指针。

 /*
public class ListNode {
int val;
ListNode next = null; ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1==null||pHead2==null)
{return null;}
ListNode temp1 = pHead1;
ListNode temp2 = pHead2;
int length1=0;
int length2=0;
while(temp1!=null){
length1++;
temp1 = temp1.next;
}
while(temp2!=null){
length2++;
temp2 = temp2.next;
}
int diff= Math.abs(length1-length2);
if(length1>=length2){
for(int i=0; i<diff; i++){
pHead1 = pHead1.next;
}
}else{
for(int i=0; i<diff; i++){
pHead2 = pHead2.next;
}
}
while(pHead1!=pHead2){
pHead1 = pHead1.next;
pHead2 = pHead2.next;
} return pHead1; }
}