Eastern Monk
Eastern Monk

Reputation: 6635

Detecting cycle in a singly linked list

Detecting cycles in a single linked list is a well known problem. I know that this question has been asked a zillion times all over the internet. The reason why I am asking it again is I thought of a solution which I did not encounter at other places. (I admit I haven't searched that deeply either).

My solution is:

Given a linked list and pointer to some node, break the link between node and node->next(); Then start at node->next() and traverse till either you hit an end (which means there was no loop) or till you reach at node which means there was a loop.

Is there anything wrong/good about above solution ?

Note: Do join the link back once you are done.

Upvotes: 1

Views: 559

Answers (3)

TheMaskedCucumber
TheMaskedCucumber

Reputation: 2019

You are not allowed to break a link, even if you join it back at the end. What if other programs read the list at the same time ?

The algorithm must not damage the list while working on it.

Upvotes: 0

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77454

I guess the most trivial approach (not necessarily the best, but one that everybody should know how to implement in Java in a few lines of code) is to build a Hash Set of the nodes, start adding them until you find one that you already saw before. Takes extra memory though.

If you can mark nodes, start marking them until you find one you marked before (the hash map is essentially an external marker).

And check the usual graph theory books...

Upvotes: 0

Gian
Gian

Reputation: 13945

That will work to detect complete cycles (i.e., cycles with a period of the whole list), e.g.:

A -> B -> C -> D -> A

But what if we have a cycle somewhere else in the list?

e.g.,

A -> B -> C -> D -> E -> C

I can't see that your algorithm will detect the cycle in this case.

Keep in mind that to detect the first case, we need not even break the link. We could just traverse the list and keep comparing the next link for each node with the head element to see if we'd started back at the start yet (or hit the end).

Upvotes: 2

Related Questions