How can one find a cycle in the linked list? IF found how
to recognize the cycle and delete that cycle?

Answer Posted / chethu

Why are you guys moving both the pointers one behind the other?
You can keep a pointer at the header and traverse the other and check if it comes back to header if it does then there is a cycle else there is no cycle..

bool find_cycle(Node* head){
Node* ptr1 = head;
Node* ptr2 = head->next;

while(ptr2 != NULL && ptr2->next != NULL)
{
if(ptr1 == ptr2){
printf("\nClycle present in thr LinkList\n");
return true;
}
ptr2 = ptr2->next->next;
}
return false;
}

This should be more efficient.

Is This Answer Correct ?    1 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is the best case for bubble sort?

470


What is adt example?

534


Define heap order property?

542


Which one is the simplest sorting in data structure?

619


Which is better arraylist or linkedlist?

451






Why is hashing used?

455


Can we extend an array after initialization?

569


Why do we need to use computers to help us sort lists?

560


What is a hash in programming?

480


Why do we use different types of data structures?

465


What is data structure geeksforgeeks?

632


Does arraylist contain duplicates?

466


Which sorting technique is best?

515


How do you sort pseudocode?

488


What is the height of binary tree?

495