Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Saturday, July 29, 2017

Remove Loop from Linked List


We will initialize two pointers slow and fast which moves 1 and 2 steps respectively.


If they met it means that there is a loop and then we will move them again and this time fast pointer will point to last node so Point its next to null


Code


class dmg{
 int removeTheLoop(Node node) {
int flag=0;
Node slow=node;
Node fast=node;
while(fast!=null && fast.next!=null && slow!=null)
{
    fast=fast.next.next;
    slow=slow.next;
    if(slow==fast)
    {
        flag=1;
        break;
    }
}
 if(slow==fast)
 {
     while(fast!=null && fast.next!=null && slow!=null)
{
    fast=fast.next.next;
    slow=slow.next;
    if(slow==fast)
    {
        break;
    }
}
fast.next=null;
 }
 return flag;
}
}

0 Comments:

Post a Comment

Stats