/*
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 h1 = pHead1;
ListNode h2 = pHead2;
int len1 = 0;
int len2 = 0;
//遍历以获取长度
while (h1 != null) {
h1 = h1.next;
len1++;
}
while (h2 != null) {
h2 = h2.next;
len2++;
}
//求出长短差值
int diff = 0;
ListNode longList, shortList;
if (len1 > len2) {
longList = pHead1;
shortList = pHead2;
diff = len1 - len2;
} else {
shortList = pHead1;
longList = pHead2;
diff = len2 - len1;
}
//长链表先走diff 步
for (int i = 0; i < diff; i++) {
longList = longList.next;
}
//长短链表在不为空的情况下比较值大小
while (longList != null && shortList != null && longList.val != shortList.val) {
longList = longList.next;
shortList = shortList.next;
}
return shortList;
}
}