2.7 Intersection

Simple linked list problem.
Time complexity: O(n).

    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        // write your code here
        if(!headA || !headB) return NULL;
        ListNode* p = headA;
        ListNode* q = headB;
        while(p && q && p != q){
            p = p->next;
            q = q->next;
            if(p == q) return p;
            if(!p->next) p = headB;
            if(!q->next) q = headA;
        }
        return p;// two list intersected at head;
    }

你可能感兴趣的:(LinkedList)