llllmz

导航

面试题 02.07. 链表相交

明天回家喽,最近在学习的瓶颈期,感觉学的东西好难,有厌学的心理,但是我相信过了这段煎熬的时期,就好了。

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int na = 0, nb = 0;
        ListNode* tempA = headA;
        ListNode* tempB = headB;
        while(tempA){
            ++na;
            tempA = tempA->next;
        }
        while(tempB){
            ++nb;
            tempB = tempB->next;
        }
        int n = na- nb;
        if(nb > na){
            tempA = headB;
            tempB = headA;
            n = nb - na;
        }else{
            tempA = headA;
            tempB = headB;
        }
        while(n){
            tempA = tempA->next;
            --n;
        }
        while(tempA){
            if(tempA == tempB) return tempA;
            tempA = tempA->next;
            tempB = tempB->next;
        }
        return NULL;
    }   
};

 

posted on 2024-09-28 21:37  神奇的萝卜丝  阅读(21)  评论(0)    收藏  举报