1. 程式人生 > >160. Intersection of Two Linked Lists

160. Intersection of Two Linked Lists

listnode 我們 truct rst spec null cond retain stop

Write a program to find the node at which the intersection of two singly linked lists begins.


For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3
begin to intersect at node c1.


Notes:

If the two linked lists have no intersection at all, 
return null. The linked lists must retain their original structure after the function returns. You may assume there are no cycles anywhere in the entire linked structure. Your code should preferably run in O(n) time and use only O(1) memory. Credits: Special thanks to @stellari for adding this problem and creating all test cases.

第一想法是用HashSet<ListNode>, A list先遍歷,存HashSet,然後B list遍歷,發現ListNode存在就返回。但是這個方法不滿足O(1)memory的要求。

再想了一會兒,略微受了點提醒,發現可以利用這個O(n) time做文章。這個條件方便我們scan list幾次都可以。於是我想到了:

先scan A list, 記錄A list長度lenA, 再scan B list, 記錄B list長度lenB. 看A list最後一個元素與 B list最後一個元素是否相同就可以知道是否intersect.

各自cursor回到各自list的開頭,長的那個list的cursor先走|lenA - lenB|步,然後一起走,相遇的那一點就是所求

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    int lenA = length(headA), lenB = length(headB);
    // move headA and headB to the same start point
    while (lenA > lenB) {
        headA = headA.next;
        lenA--;
    }
    while (lenA < lenB) {
        headB = headB.next;
        lenB--;
    }
    // find the intersection until end
    while (headA != headB) {
        headA = headA.next;
        headB = headB.next;
    }
    return headA;
}

private int length(ListNode node) {
    int length = 0;
    while (node != null) {
        length++;
        node = node.next;
    }
    return length;
}

  ote最高的做法:no need to calculate the difference in length. two pointers starts from both head. When one reach the end just set it at the head of another list. When two pointers join, that‘s the intersection

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