JC专题

Intersection of Two Linked Lists

2016-11-11  本文已影响173人  郑明明
A:     a1 → a2
                     ↘
                       c1 → c2 → c3
                     ↗            
B:     b1 → b2 → b3

begin to intersect at node c1.

Notes:

    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode *nodeA = headA;
        ListNode *nodeB = headB;
        int lengthA = 0; 
        int lengthB = 0;
        while(headA) {
            lengthA++;
            headA = headA->next;
        }
        while(headB) {
            lengthB++;
            headB = headB->next;
        }
        if (lengthA >= lengthB) {
            int difference = lengthA - lengthB;
            for (int i = 0; i < difference; i++) {
                nodeA = nodeA->next;
            }
        } else {
            int difference = lengthB - lengthA;
            for (int i = 0; i < difference; i++) {
                nodeB = nodeB->next;
            }
        }
        while(nodeA!=nodeB) {
            nodeA = nodeA->next;
            nodeB = nodeB->next;
        }
        return nodeA;
    }
上一篇下一篇

猜你喜欢

热点阅读