Monday, April 22, 2019

Remove Loop From Linked List using Floyd's Algorithm



C++ Code:


void remove_loop(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->next != fast->next){
        slow = slow->next;
        fast = fast->next;
    }
    fast->next = nullptr;
}



Detailed explanation is available 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...