两个链表的第一个公共结点
题目
输入两个链表,找出它们的第一个公共结点。
示例
示例 1:
1, 2, 3, 4, 5, 6, 7, 8, 9
10,11, 4, 5, 6, 7, 8, 9
返回4
解题
思路
两个链表定义两个指针指向头节点,然后同时一步一步指向next,当next为null时,分别指向对方的头结点。
直到指针指向的引用为同一个对象就是所求, 因为两个相交链表只有相交点前面的长度可能不一致,每个指针走了对方的,肯定会在相交点相聚。
注意考虑根本没有环的情况,别死循环了
代码
public class FindFirstCommonNode {
public static void main(String[] args) {
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(2);
ListNode l3 = new ListNode(3);
ListNode l4 = new ListNode(4);
ListNode l5 = new ListNode(5);
l1.next = l2;
l2.next = l4;
l4.next = l5;
System.out.println(findFirstCommonNode(l1,l3).val);
}
public static ListNode findFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode point1 = pHead1;
ListNode point2 = pHead2;
int count = 0;
while (point1 != point2) {
if (count > 2) {
// 此时证明根本没有交点
return null;
}
point1 = point1.next;
point2 = point2.next;
if (Objects.isNull(point1)) {
point1 = pHead2;
count++;
}
if (Objects.isNull(point2)) {
point2 = pHead1;
count++;
}
}
return point1;
}
}