Linked List: Detect a Cycle in a linked list - List Reversal

Q: Find whether or not there is a cylcle in a linked list? If so, Fix the cycle.
There are several solutions to this problem. I already discussed a few soIutions prior to this. Lets look into an easy but not so commonly used solution.

Sol 5: Find Cycle through List Reversal

We've looked into some classic approaches of Linked List Cycle Finding Methods (Hare and Tortoise) in the previous posts. Lets see a more easier straightforward approach. I am a bit surprised this is not a usually used method.

The idea is pretty simple. Reverse the list!!. If you meet the head in the process of reversal, you've got a cycle. Below is some sample code for this. The exit condition, when you do not find a cycle is when you reach the tail node. Either ways the list needs to be reveresed again, so that we leave the list in its initial state.

void LinkedList::IsLooped1() {

	LNode* prev=NULL;
	LNode* current=NULL;
	LNode* tmp=head;

	while(tmp) {
		prev=current;
		current=tmp;
		tmp=tmp->next;
		if(tmp==head)
 		  cout < < "Found Loop\n";
		current->next=prev;
	}
	head=current;
	Reverse(); //Leave list in original state
}

Comments

Dmytro: This is the same

Dmytro: This is the same solution that I posted here http://www.tekpool.com/?p=14

Here is my

Here is my O(n)-solution:

struct E { E * next; };

bool has_loop( E * first )
{
if (first == 0) return false;
E * last = first->next;
for ( int len = 1; ; len *= 2 )
{
std::cout next ;
}
// expand region
for ( int i = 0; i next;
if ( last == 0 ) return false;
}
}
}

Of course, I did not mean

Of course, I did not mean circular linked lists either.. althought this would be a special case of a cycle in a list.. The algorthim works perfectly fine, with the example you mentioned.. and that is exaclty what the problem is.. If you are still in doubt reverse each link and draw it out for every step..

I guess there is a problem

I guess there is a problem with the editor. what I meant was 6 was pointing to 3!

This code will not work! We

This code will not work! We are not talking about circular linked lists but a cycle in a linked list.
If a list such as this exits:

1 -> 2 -> 3 -> 4 -> 5 -> 6
|______________|

your initial while loop will go into an infinite loop!

In your comment N3 points to

In your comment N3 points to both N4 and N6. Given the structure of a Node in a singly linked list.. this is simply not possible

Hi this wont work if you

Hi this wont work if you have internal cycles
i mean like this

N1->N2->N3->N4
| |
N6