Friday, April 19, 2019

Find First Element of Loop in Linked List




C++ Code:

void find_loop_beginning(Node *head){
    Node *slow = head;
    Node *fast = head;
    if (!head || !(head->next))
        return;
    while(slow && fast && fast->next){
        slow = slow->next;
        fast = fast->next->next;
        if(slow == fast)
            break;
    }
    
    // No Loop exixts
    if (slow != fast){
        std::cout << "No Loop" << std::endl;
        return;
    }
    
    // When Loop exists
    slow = head;
    while(slow != fast){
        slow = slow->next;
        fast = fast->next;
    }
    std::cout << "First loop element = " << slow->data << std::endl;
}

Detailed explanation can be found on Youtube:


Subscribe to KnowledgeCenter

No comments:

Post a Comment

LeetCode 30 Day Challenge | Day 7 | Counting Elements

Given an integer array  arr , count element  x  such that  x + 1  is also in  arr . If there're duplicates in  arr , count them sepe...