题目:输入两个链表,找出它们的第一个公共结点。
思路:首先遍历两个链表得到他们的长度,就能知道哪个链表比较长,以及长的链表比短的链表多几个结点。在第二次遍历的时候,在较长的链表上先走若干步,接着再同时在两个链表上遍历,找到第一个相同的结点就是他们的第一个公共结点。
public ListNode findFirstCommonNode(ListNode root1,ListNode root2){
int length1 = getLength(root1);
int length2 = getLength(root2);
ListNode pointLongListNode = null;
ListNode pointShortListNode = null;
int dif = 0;
if(length1 >length2){
pointLongListNode = root1;
pointShortListNode = root2;
dif = length1-length2;
}else{
pointLongListNode = root2;
pointShortListNode = root1;
dif = length2 - length1;
}
for(int i = 0;i<dif;i++)
pointLongListNode = pointLongListNode.next;
while(pointLongListNode != null && pointShortListNode != null && pointLongListNode != pointShortListNode){
pointLongListNode = pointLongListNode.next;
pointShortListNode = pointShortListNode.next;
}
return pointLongListNode;
}
private int getLength(ListNode root){
int result = 0;
if(root == null)
return result;
ListNode point = root;
while(point != null){
point = point.next;
result++;
}
return result;
}