题目:输入两个链表,找出它们的第一个公共结点。
思路:先得到两个链表的长度,让长的链表先遍历长的那一段距离(因为如果有公共节点,那么最后应该是同一段链表)
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1==null||pHead2==null) return null;
if(pHead1==pHead2) return pHead1;
int len1=0;
int len2=0;
ListNode pNode1 = pHead1;
ListNode pNode2 = pHead2;
while(pNode1!=null){
pNode1 = pNode1.next;
len1++;
}
while(pNode2!=null){
pNode2 = pNode2.next;
len2++;
}
if(len1>len2){
int moreLen = len1-len2;
while(moreLen>0){
pHead1 = pHead1.next;
moreLen--;
}
}else{
int moreLen = len2-len1;
while(moreLen>0){
pHead2 = pHead2.next;
moreLen--;
}
}
while(pHead1!=pHead2&&pHead1!=null){
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
return pHead1;
}