剑指offer 52:两个链表的第一个公共节点

在这里插入图片描述
两个链表互相走过对方的路,就相遇了
A: a1->a2->c1->c2->c3->b1->b2->b3->c1
B: b1->b2->b3->c1->c2->c3->a1->a2->c1
如果不相交,两个链表也会相遇在NULL

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

猜你喜欢

转载自blog.csdn.net/weixin_44537258/article/details/114156301