Sword refers to offer 52. The first common node of two linked lists (by walking each other's path, you can reach the end together!)

Tuesday, February 2, 2021, the weather is fine [Don’t lament the past, don’t waste the present, don’t fear the future]


Problem-solving ideas:

Side analysis : as a whole, after you have walked your own way, you will go to the other side's way. When you reach the end for the second time, both of them will take a M+Nstep and push back, and then the two will go back for the first time. The point of meeting is what you want.

Direct analysis : When the second person reaches the end, the first person just finished the difference between the two, so if they walk together later, they will meet at the first common point.

class Solution {
    
    
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
    
    
        if(headA==nullptr || headB==nullptr) return nullptr;
        ListNode *hA = headA, *hB = headB;
        while(hA!=hB){
    
    
            hA = hA?hA->next:headB;
            hB = hB?hB->next:headA;
        }
        return hA;
    }
};

references

"Sword Finger Offer Second Edition"

https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/solution/shuang-zhi-zhen-fa-lang-man-xiang-yu-by-ml-zimingm/

Guess you like

Origin blog.csdn.net/m0_37433111/article/details/113555948