输入两个链表,找出它们的第一个公共结点。
1)两个链表无环情况下面代码
2)一个有环,一个没环没交点
2)如果两个都有环,则可能比较复杂,因为存在一个入口节点和两个入口节点,可以通过节点标记进行遍历获取入口节点
/**
* 必须有节点,否则可能会引起死循环
*
* @author Joeson Chan
*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(null == pHead1 || null == pHead2){
return null;
}
ListNode index1 = pHead1;
ListNode index2 = pHead2;
while(index1 != index2){
index1 = null == index1 ? pHead2 : index1.next;
index2 = null == index2 ? pHead1 : index2.next;
}
return index1;
}
}
本文介绍了一种高效算法,用于查找两个链表的第一个公共节点。适用于无环链表,并提供了一个简洁的 Java 实现。该算法通过双指针同步遍历的方法,在 O(n) 时间复杂度内找到公共节点。

被折叠的 条评论
为什么被折叠?



