题目描述
输入两个链表,找出它们的第一个公共结点。
代码实现
/*
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;
if(pHead1 == pHead2)
return pHead1;
int length1 = 0,length2 = 0;
ListNode current1 = pHead1;
ListNode current2 = pHead2;
while(current1 != null){ //计算pHead1的长度
length1++;
current1 = current1.next;
}
while(current2 != null){ //计算pHead2的长度
length2++;
current2 = current2.next;
}
int llength = 0;
//走完pHead1或者pHead2多余的部分
if(length1 > length2){
llength = length1 - length2;
while(llength!=0){
pHead1 = pHead1.next;
llength--;
}
}else{
llength = length2 - length1;
while(llength!=0){
pHead2 = pHead2.next;
llength--;
}
}
while(pHead1 != pHead2 && pHead1 != null){ //定位到公共结点
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
return pHead1;
}
}