Leetcode Intersection of Two Linked Lists

找两个链表中的第一个共同元素。尽量O(n)时间,O(1)空间。32ms简单题

struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
    if (!headA || !headB)   return NULL;
    int l1 = 0, l2 = 0;
    struct ListNode *p1, *p2;
    for (p1 = headA ; p1 ; p1 = p1->next)
        l1++;
    for (p2 = headB ; p2 ; p2 = p2->next)
        l2++;
    if (l1 > l2)
        for (p1 = headA, p2 = headB ; l1 != l2 ; p1 = p1->next)
            l1--;
    else
        for (p1 = headA, p2 = headB ; l1 != l2 ; p2 = p2->next)
            l2--;
    for ( ; p1 ; p1 = p1->next, p2 = p2->next)
        if (p1 == p2)
            return p1;
    return NULL;      
}
点赞