Solution in C


  • 1
    I
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
        struct ListNode *p1,*p2;
        p1 = headA;
        p2 = headB;
        while ((p1 != NULL || p2 != NULL) && p1 != p2)
        {
            p1 = p1 ? p1->next : headB;
            p2 = p2 ? p2->next : headA;
        }
        return p1;
    }
    

  • 0
    F

    @i4never
    for condition check, while ((p1 != NULL || p2 != NULL) && p1 != p2) is too much.
    just use p1 != p2, because if no intersection exists, p1 and p2 will meet each other when they are both NULL.

    if you consider that maybe headA is NULL and headB is a long linked list, then put if (!headA || !headB) return NULL at the beginning.


  • 0
    I

    @FindRX
    Yes, you're right. It will save much time! :)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.