输入两个链表,找出它们的第一个公共结点。
方法:
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
int length1=0,length2=0;
ListNode temp1,temp2;
temp1=pHead1;
while(temp1!=null){
length1++;
temp1=temp1.next;
}
temp2=pHead2;
while(temp2!=null){
length2++;
temp2=temp2.next;
}
temp1=pHead1;
temp2=pHead2;
if(length1>length2){
int num=length1-length2;
while(num>0){
num--;
temp1=temp1.next;
}
}else{
int num=length2-length1;
while(num>0){
num--;
temp2=temp2.next;
}
}
while(temp1!=null && temp2!=null){
if(temp1==temp2)
return temp1;
temp1=temp1.next;
temp2=temp2.next;
}
return null;
}
}