算中的链接列表可以是圆形的节点数 [英] Count number of nodes in a linked list that may be circular

查看:115
本文介绍了算中的链接列表可以是圆形的节点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在的问题是,它是从伊迪的优秀算法中的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).

这篇关于算中的链接列表可以是圆形的节点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆