题目:输入两个链表,找出它们的第一个公共结点。
package offer;
/*
* 两个链表的第一个公共结点
*/
public class FindFirstCommonNode {
public static ListNode findFirstCommonNode(ListNode root1, ListNode root2){
int length1 = getListLength(root1);
int length2 = getListLength(root2);
int lengthDif = length1 - length2;
ListNode headLong = root1;
ListNode headShort = root2;
if(length2>length1){
headLong = root2;
headShort = root1;
lengthDif = length2 - length1;
}
//先在长链表上走几步
for(int i=0; i<lengthDif; i++)
headLong = headLong.next;
while(headLong!=null && headShort!=null && headLong != headShort){
headLong = headLong.next;
headShort = headShort.next;
}
//得到第一个公共结点
ListNode commonNode = headLong;
return commonNode;
}
private static int getListLength(ListNode root){
int length=0;
ListNode head = root;
while(head!=null){
length++;
head = head.next;
}
return length;
}
}