算中的链接列表可以是圆形的节点数节点、圆形、链接、列表

2023-09-11 04:08:02 作者:傲娇孤人

现在的问题是,它是从伊迪的优秀算法中的Java(Q 3.54)

Here is the problem, it is from Sedgwick's excellent Algorithms in Java (q 3.54)

鉴于单链接列表,其中包含没有空链路(即每个节点或者链接到其自身或列表中的另一个节点)确定不同的节点数量,而无需修改任何一个节点并且不使用更多的链接的节点超过一定的存储空间。

Given a link to a node in a singly linked list that contains no null links (i.e. each node either links to itself or another node in the list) determine the number of different nodes without modifying any of the nodes and using no more than constant memory space.

你怎么办呢?通过使用龟兔赛跑算法一旦制定出是否是圆形的以任何方式,然后通过再次扫描工作,哪里出了列表变为圆形清单扫描,然后通过再次计算节点的数量,这个位置扫描?听起来有点蛮力给我,我想有更优雅的解决方案。

How do you do it? scan through the list once using the hare and tortoise algorithm to work out whether it is circular in any way, and then scan through again to work out where the list becomes circular, then scan through again counting the number of nodes to this position? sounds a bit brute-force to me, I guess there is much more elegant solution.

推荐答案

的的乌龟和野兔算法可以给你的两个的周期长度和节点数量的前周期开始(λ和μ分别)。

The tortoise and hare algorithm can give you both the cycle length and the number of nodes before the cycle begins (λ and μ respectively).