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 happens in insertion sort?

586


Given an unsorted linked list, and without using a temporary buffer, write a method that will delete any duplicates from the linked list?

719


Why do we use insertion sort?

555


Does treemap allow null values?

541


What is queue example?

570






What are the different types of collections?

575


What is a pseudocode example?

578


Which programming language is best for data structures?

552


What is stack algorithm?

543


Why is quicksort so fast?

566


Which interfaces are implemented by concurrentskiplistset?

572


State the advantages of using infix notations?

765


What is data algorithm?

611


Can we extend an array after initialization?

661


What happens when arraylist is full?

583