C++ another solution using the code of "finding the loop beginning"

  • 5
    class Solution {
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if (headA==NULL || headB==NULL) return NULL;
        if (headA==headB) return headA;
        ListNode *tailA=headA;
        while (tailA->next!=NULL){
        tailA->next = headB;
        ListNode *slow=headA,*fast=headA;
        while (fast!=NULL && fast->next!=NULL){
            fast = fast->next->next;
            slow = slow->next;
            if (slow==fast){
                fast = headA;
                while (fast!=slow){
                    fast = fast->next;
                    slow = slow->next;
                tailA->next = NULL;
                return fast;
        tailA->next = NULL;
        return NULL;

Log in to reply

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