思路:获取两个链表的长度,求的长度差n,让长链表先遍历n次,然后长链表和短链表同时遍历,当长链表和短链表相等时,即为第一公共结点。(O(m1+m2))
public class FindFirstComNode {
public static ListNote findFirstComNode(ListNote root1,ListNote root2){
if(root1==null||root2==null){
return null;
}
int len1=getNodeLength(root1);
int len2=getNodeLength(root2);
int count=(len1-len2)>0?(len1-len2):(len2-len1);
ListNote longListNote=(len1-len2)>0?root1:root2;
ListNote shortListNote=(len1-len2)>0?root2:root1;
int i=0;
while((longListNote!=null)&&(shortListNote!=null)&&longListNote!=shortListNote){
i++;
longListNote=longListNote.getNext();
if(i>count){
shortListNote=shortListNote.getNext();
}
}
ListNote firstComNode=longListNote;
System.out.println(firstComNode.getValue());
return firstComNode;
}
public static int getNodeLength(ListNote root){
if(root==null){
return 0;
}
int len=0;
while(root!=null){
len++;
root=root.getNext();
}
return len;
}
}