输入两个链表,找出它们的第一个公共结点。
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;
}
}