views:

222

answers:

2

http://stackoverflow.com/questions/1285560/how-do-you-remove-a-cycle-in-a-single-linked-list

Before I write some sample code to do what this answer describes, does anyone already have a C# example of repairing a singly linked list that points back into itself?

I understand the detection part (tortoise/hare) but the repair part is a little fuzzy to me.

+1  A: 

You find the "start" of the cycle. This is the node that has more than one node connecting to it.

One of those nodes will be from the head of the list - you want to leave this one alone.

The other node is the one you want to change - typically you make it connect to null, indicating the end of the list.

Anon.
+3  A: 

The article you linked to has algorithms which allow you to compute the node which has two references, one from the start of the list and one from the node that should be the "end" of the list. If you can find that node, then surely you can find the node that should be the end of the list. Find that node. Set its "next" reference to null.

My recommendation: draw lots and lots of boxes and arrows on your whiteboard. Understand how the algorithm works by manually running through it a half-dozen times on the board. Once you understand how it works visually, it will be a lot more straightforward to write the code. (My whiteboard is usually chock-full of boxes and arrows in about a dozen different colours for this reason...)

Eric Lippert
yeah ... I was just wanting to be lazy and use my favourite code - someone else's. This is my weekend project.
No Refunds No Returns
No code found ... I wrote my own. There are lots of ways to be "off by 1" but I have some code that works consistently. Go Cowboys! Beat Saints! (Oh wait ... did they ever!)
No Refunds No Returns