Method1: Detect and remove loop in a linked list
1. detect loop
2. store the address of the common node in a pointer
3. put slow pointer on head
4. move both pointers by unit 1
5. Now make the next of the common node found again point to null.
Detect loop using Floyd cycle detection algorithm and then
#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 loop ends
return 0;
} //int ends
void remloop(struct node* loop_node , struct node* head)
{
struct node *ptr1;
struct node *ptr2;
ptr1= head;
while(1)
{
ptr2 = loop_node;
while(ptr2->next !=loop_node && ptr2->next != ptr1)
ptr2= ptr2->next;
if(ptr2->next==ptr1) break;
ptr1=ptr1->next;
} //while loop ends
ptr2->next= NULL;
} //f ends
void printlist(struct node* node)
{
while(node!= NULL){
cout<<node->data<< " ";
node=node->next;} //while ends
} //f ends
struct node* newnode(int key)
{
struct node* temp= new node();
temp->data= key;
temp->next= NULL;
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