题目:
看到这个题,我想到的就是最笨的办法,先遍历两个链表,算出各自的长度,然后让长的链表先走Math.abs(l1-l2)步,然后两个指针再一起走,当指向同一个节点时就找到了公共节点。
虽然觉得这个办法太老了,但是暂时也没有想到新方法。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1 == null || pHead2 == null)
return null;
int l1 = getLen(pHead1);
int l2 = getLen(pHead2);
if(l1 > l2)
return getCon(pHead1,pHead2,l1-l2);
return getCon(pHead2,pHead1,l2-l1);
}
public int getLen(ListNode tmp){
int res = 0;
while(tmp != null){
res++;
tmp = tmp.next;
}
return res;
}
public ListNode getCon(ListNode p1,ListNode p2,int len){
for(int i = 0; i < len; i++){
p1 = p1.next;
}
while(p1 != null && p2 != null){
if(p1.val == p2.val)
return p1;
p1 = p1.next;
p2 = p2.next;
}
return null;
}
}