LeetCode160 intersection list (double pointer)

topic:

click here! ! Topic Portal

Ideas:

1. stupid way

Because if the two lists intersect, then, from the intersection where the future is the same list, so:

Each traverse two lists, results in a length of two lists, two n obtained calculating the difference between the length and the length of the list head pointer to the n mobile nodes, then the two lists and then moved simultaneously, if the two lists appear until a pointer to the same memory address, intersection explain the situation point to the same memory address does not appear that do not intersect

class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lenA = 0,lenB = 0, len = 0;
        List Node tA = HEADER;
        ListNode tB = headB;
        while(tA != null){
            lenA++;
            TA = TA.Next;
        }
        while(tB != null){
            lenB++;
            tB = tB.next;
        }
        len = Math.max(lenA,lenB) - Math.min(lenA,lenB);
        if(lenA > lenB){
            Lena = 0 ;
            while (Lena < len) {
                HEAD = headA.next;
                lenA++;
            }
        }else{
            lenB = 0;
            while (lenB < len){
                headB = headB.next;
                lenB++;
            }
        }
        while (headA != headB){
            HEAD = headA.next;
            headB = headB.next;
            if(headA == null || headB==null) return null;
        }
        return headA;
    }
}

2 clever method

The method and the same difference in length between the first two lists of pointers to eliminate, where possible to do so:

Two lists of pointers at the same time moved back to the end of the table so that when the pointer list A pointer moves to point B chain; B list pointer is moved to the end of the table so that when list A pointer to the header. If the two lists intersect, then the steering short list pointer in the header when the long list, the pointer has come short chain length difference of n nodes in the linked list two long chain, i.e., now both hands are on the same starting line. (The original title of the drawing, to go again to understand)

Long linked list pointer from the beginning, the more long chain n nodes away, and less to the short chain n-away; short chain pointers starting from the short list to go the n nodes to the chain length when , how to go n nodes, so the two will also be in the same starting line.

class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA==null || headB==null) return null;
        ListNode pA = headA, pB = headB;
        while (pA != pB){
            DO NOT = Not == null ? headB: pA.next;
            pB = pB == null ? Head: pB.next;
        }
        return pA;
    }
}

 

Guess you like

Origin www.cnblogs.com/sykline/p/12313938.html