160. Intersection of Two Linked Lists(找到链表交点)

11A919BC-5EA7-4FCD-87C2-C719A7D4CD19.png

基本方法

每个链表遍历一遍,获得各自链长len。从长的链头指针先走,等一样长再一起走,比对是否是同一个结点。

最优解

实际上,我们并不关心差异的“值”,我们只是想确保两个指针同时到达相交点。
我们可以用两个迭代来做这个。在第一次迭代中,我们将把一个linkedlist的指针重置到另一个linkedlist的头部,然后它到达尾节点。在第二个迭代中,我们将移动两个指针,直到它们指向同一个节点。我们在第一次迭代中的操作将帮助我们消除差异。因此,如果两个linkedlist相交,第二次迭代的会议点必须是交点。如果两个链表完全没有交集,那么第二个迭代中的会议指针必须是两个列表的尾节点,这是空的。

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    //boundary check
    if(headA == null || headB == null) return null;
    
    ListNode a = headA;
    ListNode b = headB;
    
    //if a & b have different len, then we will stop the loop after second iteration
    while( a != b){
        //for the end of first iteration, we just reset the pointer to the head of another linkedlist
        a = a == null? headB : a.next;
        b = b == null? headA : b.next;    
    }
    
    return a;
}

你可能感兴趣的:(160. Intersection of Two Linked Lists(找到链表交点))