题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
http://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
int len1 = Length(pHead1);
int len2 = Length(pHead2);
while(len1!=len2){
if(len1>len2){
pHead1 = pHead1.next;
len1--;
}
else if(len1<len2){
pHead2 = pHead2.next;
len2--;
}
}
while(pHead1!=null && pHead2!=null){
if(pHead1==pHead2) return pHead1;
else {
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
}
return null;
}
public int Length(ListNode l){
int cnt = 0;
while(l!=null){
cnt++;
l = l.next;
}
return cnt;
}
}
由于不是有序排布的,那么考虑其长度,