Remove loop in Linked List | Practice | GeeksforGeeks

Given a linked list of N nodes such that it may contain a loop. 
A loop here means that the last node of the link list is connected to the node at position X. If the link list does not have any loop, X=0.
Remove the loop from the linked list, if it is present.  

Example 1:
Input:
N = 3
value[] = {1,3,4}
X = 2
Output: 1
Explanation: The link list looks like
1 -> 3 -> 4
     ^    |
     |____|    
A loop is present. If you remove it 
successfully, the answer will be 1. 


Example 2:
Input:
N = 4
value[] = {1,8,3,4}
X = 0
Output: 1
Explanation: The Linked list does not 
contains any loop. 

Example 3:
Input:
N = 4
value[] = {1,2,3,4}
X = 1
Output: 1
Explanation: The link list looks like 
1 -> 2 -> 3 -> 4
|______________|
A loop is present. 
If you remove it successfully, 
the answer will be 1. 

Your Task:
You don't need to read input or print anything. Your task is to complete the function removeLoop() which takes the head of the linked list as the input parameter. Simply remove the loop in the list (if present) without disconnecting any nodes from the list.
Note: The generated output will be 1 if your submitted code is correct.

Expected time complexity: O(N)
Expected auxiliary space: O(1)

Constraints:
1 ≤ N ≤ 104
0
rissabhpassion1 day ago
class Solution{   //Function to remove a loop in the linked list.   public static void removeLoop(Node head){       if(head == null) return;       Node startOfLoop = detectFirstNode(head);       if(startOfLoop == null) return;       Node temp = startOfLoop;       while(temp.next != startOfLoop){           temp = temp.next;       }       temp.next = null;   }      static Node detectFirstNode(Node head) {       if(head == null) return null;       Node meet = detectCycle(head);       if(meet == null) return null;       Node start = head;       while(start != meet){           start = start.next;           meet = meet.next;       }       return start;   }      static Node detectCycle(Node head) {       if(head == null) return null;       Node slow = head;       Node fast = head;       while(fast != null && fast.next != null){           fast = fast.next.next;           slow = slow.next;           if(fast == slow){               return slow;           }       }       return null;   }   }
+1
ashutosh27062 days ago
JAVA:
 
HashSet<Node> set = new HashSet<>();
        Node temp=head;
        while (temp.next!=null) {
            set.add(temp);
            if(set.contains(temp.next)) { temp.next = null; return; }
            temp=temp.next;
        }
0
tyagipriyanshi0212 days ago
am getting segmentation fault i don't kn0w why plz help??


#include<bits/stdc++.h>
class Solution
{
   public:
   //Function to remove a loop in the linked list.
   void removeLoop(Node* head)
   { vector<int> arr;
    Node *p=head,*r;
   arr[0]=head->data;
   p=p->next; int i=1;
    while(1)
    { 
        if (binary_search(arr.begin(), arr.end(),p->data))
      { r->next=NULL;
         break; }
       else
       { arr[i]=p->data;
         i++; r=p;
         p=p->next; } }
       
       
       
       // code here
       // just remove the loop without losing any nodes
   }
};
0
venkateshnagumantri013 days ago
just check for the node that is connected at end that is connected to another node in list , then remove the connection.
def removeLoop(self, head):
        # code here
        # remove the loop without losing any nodes
        curr=head
        lis=set()
        while curr!=None:
            if curr not in lis:
                lis.add(curr)
                p=curr
                curr=curr.next
            else:
                p.next=None
                break
            
        return head
+2
bansal123aryan3 days ago
In this basically we first need to to retreive the first node of loop,
then get the tail node and change its next pointer to null.
REMEMEBER : It is important to take care of base cases that it doesn't contain loop.
 
 void removeLoop(Node* head)   {       // code here       // just remove the loop without losing any nodes              Node *slow=head;       Node *fast=head;       if(slow==NULL || slow->next==NULL) return;              slow=slow->next;       fast=fast->next->next;       if(fast==NULL) return;       while(fast!=NULL &&fast->next!=NULL){                     if(slow==fast) break;           slow=slow->next;           fast=fast->next->next;                  }       if(fast==NULL || fast->next==NULL) return;              slow=head;       while(fast!=slow){           slow=slow->next;           fast=fast->next;       }       //slow will get u first meeting node       //now get the tail node              while(fast->next!=slow){           fast=fast->next;       }
// change the next pointer of tail node to NULL       fast->next=NULL;       return;                        }
0
pankaj216pant5 days ago
Please tell me what I am doing wrong.
 
 
void removeLoop(Node* head)   {       map<Node*, int> u_map;       if(head==NULL)        return;              Node *curr,*pre;       if(head->next ==head)          head->next = NULL;              curr = head;       pre = NULL;       while(curr != NULL && curr->next !=NULL){           if(u_map[curr]==0){               u_map[curr]=1;               pre = curr;               curr = curr->next;           }           else{               pre ->next = NULL;               break;           }       }   
0
aviralg20021 week ago
void removeLoop(Node* head)
    {
        if(head->next == head)
        {
            head->next =NULL;
            return;
        }
        
        Node *slow = head, *fast = head;

        while(fast!=NULL and fast->next !=NULL)
        {
            fast = fast->next->next;
            slow = slow->next;
            
            // If head is in loop
            if(slow->next == head)
            {
                slow->next = NULL;
                return;
            }
            
            // any node except head is in loop
            if(fast == slow)
            {
                slow = head;
                while(slow->next != fast->next)
                {
                    slow = slow->next;
                    fast = fast->next;
                    
                }
                
                fast->next = NULL;
                
                    
                return;
            }
        }
        return;
    }
0
akshatarora
This comment has been flagged for violating our community guidelines.
0
akshatarora
This comment was deleted.
0
akshatarora
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.