一、题目内容
二、题解
解法1:
思路
分别计算两个链表长度作差,减去差值后遍历链表最后一定相等,null,或者相交
代码
public class Solution {public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {ListNode a = pHead1;ListNode b = pHead2;int lena = 0,lenb = 0;while(a!=null){a = a.next;lena++;}while(b!=null){b = b.next;lenb++;}int d = lena-lenb;if(d>0){while(d-->0){pHead1 = pHead1.next;}}else{while(d++<0){pHead2 = pHead2.next;}}while(pHead1!=pHead2){pHead1 = pHead1.next;pHead2 = pHead2.next;}return pHead1;}}
解法2:
思路
a+(b-c) = b+(a-c) => a+b-c = b+a-c
c>0:相交,a=b
c=0:不相交,a=b=null
代码
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode a = pHead1;
ListNode b = pHead2;
while(a!=b){
a = a!=null? a.next:pHead2;
b = b!=null? b.next:pHead1;
}
return a;
}
}
