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

Is queue fifo or lifo?

646


Is it possible to increase size of array?

679


What do you mean by union-by-weight?

740


What do u mean by array?

666


Can you store different types in an array?

684


How would you reverse characters of an array without using indexing in the array.

671


Can you override methods of arraylist?

671


Does hashmap preserve insertion order?

663


How does hashset work internally in java?

704


How to inverting a function in sort and searching?

654


What is nsmutablearray?

613


What is a bubble sort and how do you perform it?

824


Explain the term base case?

688


Define circular list?

760


How can you insert a node in a random location of the linked list?

669