I was inspired by "Linked List Cycle II ",and beat 96% cpp's users:


  • 0
    Y

    ListNode* hasCycle2(ListNode head) {
    ListNode
    p,*q,*r;
    p=q=r=head;
    while(q!=NULL && q->next!=NULL)
    {
    p=p->next;
    q=q->next->next;
    if(p==q)
    {
    while(p!=r)
    {
    p=p->next;
    r=r->next;
    }
    return p;
    }
    }
    return NULL;
    }
    ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    ListNode
    p=headA;ListNode
    endA;
    if(headA==NULL || headB==NULL)return NULL;
    while(p!=NULL && p->next!=NULL)
    {
    p=p->next;
    }
    endA=p;
    endA->next=headA;
    ListNode
    out=hasCycle2(headB);
    endA->next=NULL;
    return out;
    }


Log in to reply
 

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