开发者

Does anyone have C# code to repair a linked list that cycles?

how do you remove a cycle in a single linked list?

Before I write some sample code to do what this an开发者_JS百科swer 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.


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...)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜