题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
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) {
ListNode p1 = pHead1;
ListNode p2 = pHead2;
//1先遍历一遍 获取链表长度
int plen1 = 0,plen2 = 0;
while(p1!=null){
plen1++;
p1 = p1.next;
}
while(p2!=null){
plen2++;
p2 = p2.next;
}
//2确定长短链表 ,并创建2个数组存放链表节点
int maxlen = plen1>plen2 ? plen1:plen2;
int minlen = maxlen==plen2? plen1:plen2;
ListNode[] arr1 = new ListNode[maxlen];
ListNode[] arr2 = new ListNode[maxlen];
ListNode maxNode = maxlen == plen2? pHead2 : pHead1;
ListNode minNode = maxNode == pHead1? pHead2 : pHead1;
//存放链表节点
int i=0;
while(maxNode!=null){
arr1[i] = maxNode;
i++;
maxNode = maxNode.next;
}
i= maxlen- minlen;
while(minNode!=null){
arr2[i] = minNode;
i++;
minNode = minNode.next;
}
//3倒叙 取数组内链表节点,比较值,相同就赋值给输出指针,不同就终止
ListNode res = null;
for(int j=maxlen-1;j>=maxlen-minlen;j--){
if(arr1[j].val == arr2[j].val){
res = arr1[j];
}else{
break;
}
}
return res;
}
}