Question:
How to remove the loop from the linked list using C++

Summary

If the loop is present, remove it from the linked list by unlinking the final node that forms the loop.


Solution


/*

structure of linked list node:


struct Node

{

    int data;

    Node* next;

    

    Node(int val)

    {

        data = val;

        next = NULL;

    }

};


*/


class Solution

{

    public:

    //Function to remove a loop in the linked list.

    void removeLoop(Node* head)

    {

        // code here

        // just remove the loop without losing any nodes

        // if(head==NULL||head->next==NULL)return;

        Node *fast = head;

        Node *slow = head;

      

        while(fast!=NULL&&fast->next!=NULL){

            slow = slow->next;

            fast= fast->next->next;

            if(slow==fast)break;

        }

        

        if(slow!=fast)return;

      

        slow = head;

        while(slow!=fast){

            slow=slow->next;

            fast = fast->next;

        }

             while(slow!=fast->next){

          fast=fast->next;

             }

        fast->next=NULL;

    }

};


Explanation

Initialization of Pointers:

  • Two pointers, slow and fast, are initialized to the head of the linked list. The fast pointer is initially advanced by two steps, and the slow pointer by one step.


Loop Detection:

  • The code enters a loop where it checks for a loop using the condition fast != NULL && fast->next != NULL.


Finding the Starting Point of the Loop:

  • After detecting the loop, one pointer (slow) is moved back to the head.


Answered by:> >kanu0311

Credit:> >GeekforGeeks


Suggested blogs:

>How to configure python in jmeter?

>How to mock a constant value in Python?

>Creating a pivot table by 6 month interval rather than year

>How to Install mariaDB client efficiently inside docker?

>Can I call an API to find out the random seed in Python `hash()` function?

>How remove residual lines after merge two regions using Geopandas in python?


Submit
0 Answers