Thursday, January 28, 2021

Method2: Detect and remove loop(count nodes)

 By counting number of nodes in the loop

1. Detect loop

2. Count no of nodes in the loop.(say k)

3. Put 1 pointer on head and other at k units apart from pointer1.

4. Get the start node of the loop

5. Make the next of the start node point to NULL.

#include <iostream>

#include <bits/stdc++.h>

using namespace std;

struct node{

    int data;

    struct node* next;

};


void remloop(struct node*, struct node*);


int detandremloop(struct node* list)

{

    struct node *sp= list, *fp=list;

    while(sp && fp && fp->next)

    {

        sp=sp->next;

        fp= fp->next->next;

        if(sp==fp) {

        remloop(sp, list);

            return 1;

        } //if ends

        

    } //while ends

    return 0;

} //int ends


void remloop(struct node* loop_node, struct node* head)

{

    struct node* ptr1= loop_node;

    struct node* ptr2= loop_node;

    

    unsigned int k=1;

    while(ptr1->next!=ptr2)

    {

        ptr1= ptr1->next;

        k++;

        

    } //while ends

    

    ptr1= head;

    for (int i=0; i<k ; i++)

    ptr2= ptr2->next;

    

    while(ptr2!=ptr1) {

        ptr1=ptr1->next; ptr2= ptr2->next;

    } //whhileends

    

    while(ptr2->next!=ptr1)

    ptr2=ptr2->next;

    ptr2->next = NULL;

    

} //f ends


void printlist(struct node* node)

{

while (node!=NULL)

{

    cout<< node->data<< " ";

    node=node->next;

    

} //whileends

} //f ends


struct node* newnode(int key)

{

    struct node* temp= new node();

    temp->next= NULL; temp->data= key;

    return temp;

} //newnode ends





int main() {

  struct node* head= newnode(50);

  head->next= newnode(20);

head->next->next= newnode(15);

head->next->next->next= newnode(4);

head->next->next->next->next= newnode(10);


head->next->next->next->next->next= head->next->next;

detandremloop(head);

printlist(head);


return 0;

}


0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home