/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
}
}
- 思路
如果两个链表有公共结点,那么最后公共结点之后的部分一定是完全相同的,类似于一个“Y”的形状。我们可以先求出两个链表的长度(用len1 和len2表示)。然后长度更长的链表(假设len1 > len2)先走len1 - len2步。然后两个链表一起走。第一个相同的结点就是他们的第一个公共结点。
还要注意特殊情况:链表为空或没有公共结点。 - 我的代码
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1==null || pHead2==null) return null;
int len1 = 0, len2 = 0;
ListNode firstCommNode = null, tmp1 = pHead1, tmp2 = pHead2;
while(tmp1 != null){
len1++;
tmp1 = tmp1.next;
}
while(tmp2 != null){
len2++;
tmp2 = tmp2.next;
}
tmp1 = pHead1; tmp2 = pHead2;
if(len1 > len2){
for(int i=0; i<len1-len2; i++){
tmp1 = tmp1.next;
}
}else if (len2 > len1) {
for(int i=0; i<len2-len1; i++){
tmp2 = tmp2.next;
}
}
while(tmp1!= null && !tmp1.equals(tmp2)){
tmp1 = tmp1.next;
tmp2 = tmp2.next;
}
firstCommNode = tmp1;
return firstCommNode;
}