leetcode 160

47 阅读1分钟
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode* nodeA = headA;
        int lengthA = 0;
        ListNode* nodeB = headB;
        int lengthB = 0;
        while(nodeA!=nullptr){
            lengthA++;
            nodeA = nodeA->next;
        }         
        while(nodeB!=nullptr){
            lengthB++;
            nodeB = nodeB->next;
        }   
        nodeA = headA;
        nodeB = headB;

        //这样保证lengthA>lengthB
        if(lengthA<lengthB){
            swap(lengthA,lengthB);
            swap(nodeA,nodeB);
        }   

        int distance = lengthA - lengthB;
        while(distance--){
            nodeA = nodeA->next;
        }
        while(nodeA!=nullptr){
            if(nodeA==nodeB){
                return nodeA;
            }
            nodeA = nodeA->next;
            nodeB = nodeB->next;
        }
        return nullptr;
    }
};