C++ solution reduction to cycle finding problem


  • 0
    Q
        /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
            if(headA == NULL){
                return NULL;
            }
            auto A = headA;
            auto B = A;
            while(A != NULL){
                B = A;
                A = A -> next;
            }
            B -> next = headA;
            auto h =  detectCycle(headB);
            B -> next = NULL;
            return h;
            
        }
        ListNode *detectCycle(ListNode *head) {
            if (!head) return NULL;
    
            ListNode *fast = head, *slow = head;
            if (fast->next && fast->next->next)
            {
                do{
                    fast = fast->next->next;
                    slow = slow->next;
                }while (fast != slow && fast->next && fast->next->next);
    
                // the point is when two pointers meet, the distance from the position 
                // to the entry is equal to the distance from head to the entry
    
                if (fast == slow)
                {
                    for (fast=head; fast!=slow; fast=fast->next, slow=slow->next);
                    return fast;
                }
            }
            return NULL;
        }
        
    
    };

Log in to reply
 

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