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

Does treemap allow null values?

463


What do you mean by balanced trees?

540


What is heap with example?

517


Is it possible to make an array volatile in java?

505


What are red-black trees?

524






Why concurrenthashmap is fail safe?

509


Why might quick sort might be better than merge sort?

442


What is hashing technique?

532


how to insert a new node in linked list where free node will be available?

562


How helpful is abstract data type of data structures?

510


What does quick sort do?

485


Which data structure is used to perform recursion?

487


What is the application of queue?

476


List the area of applications of data structure.

762


What happens if we try to insert duplicate key in hashmap?

417