题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
import java.util.*;
/*
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 length1 = getLengthx(pHead1);
int length2 = getLengthx(pHead2);
while (length1 != length2) {
if (length1 > length2) {
pHead1 = pHead1.next;
length1--;
} else {
pHead2 = pHead2.next;
length2--;
}
}
while (pHead1!=pHead2) {
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
return pHead1;
}
private int getLengthx(ListNode pHead1) {
int i = 0;
while(pHead1!=null) {
pHead1 = pHead1.next ;
i++;
}
return i;
}
}
查看10道真题和解析