Intersection list three methods

link: intersection list

The first: the most ingenious way, the two lists together, A + B and B + length of A is the same length, both while traversing the list after the addition, if there is an intersection, a bound where they are equal, if there is no intersection, it will be equal to the last, because the tail of the list is null

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode a = headA;
        ListNode b = headB;
        while(a != b){
           if(a == null)
               a = headB;
           else
               a = a.next;
           if(b == null)
               b = headA;
           else
               b = b.next; 
        }
        return a;
    }

The second: I want out, calculate the length of two lists, while watching the last node are equal, if not equal, no inevitable intersection, equal if to illustrate the point of intersection. Interpolation calculation chain length, with a number of steps that go fast pointer interpolation, and then starts slow down pointer, pointing to both node is an intersection position of the same

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA ==null || headB ==null) return null;
        ListNode a = headA;
        ListNode b = headB;
        int cntA = 0;
        while (a.next != null){
            a = a.next;
            cntA++;
        }
        int cntB = 0;
        while (true){
            if(b == null) return null;
            if(b == a) break;
            b = b.next;
            cntB++;
        }
        a = headA;
        b = headB;
        if(cntA > cntB){//快指针先走长链表与短链表的插值
            int cnt = 0;
            while (cnt < (cntA-cntB)){
                a = a.next;
                cnt++;
            }
        }else{
            int cnt = 0;
            while (cnt < (cntB-cntA)){
                b = b.next;
                cnt++;
            }
        }
        while(a != null && b != null){
            if(a == b) return a;
            a = a.next;
            b = b.next;
        }
        return null;
    }

Third: I can live a title, but in fact does not meet the requirements of hashing

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        HashMap<ListNode, Integer> hm = new HashMap<>();
        ListNode a = headA;
        while(a != null){
            hm.put(a, 1);
            a= a.next;
        }
        ListNode b = headB;
        while(b != null){
            if(hm.containsKey(b)){
                return b;
            }
            b = b.next;
        }
        return null;
    }

Guess you like

Origin www.cnblogs.com/wmxl/p/11272302.html