【发布时间】:2016-05-21 20:24:14
【问题描述】:
我一直在研究一个关于代码战的谜题,可以在这里找到:
http://www.codewars.com/kata/can-you-get-the-loop
基本上,输入是链表的第一个节点,它保证有一定长度的尾部和一定长度的循环。 (图片见链接。)
我的解决方案是让两个迭代器遍历列表,一个访问每个节点,一个跳过每个节点。一旦他们命中,我就知道我在循环中,所以我只计算一个循环并返回计数。
这是我的代码:
def loop_size(node):
size = 1
onestep = node
twostep = node.next
while(onestep != twostep):
twostep = twostep.next.next
onestep = onestep.next
#we are inside the loop
#onestep == twostep
onestep = node.next
size += 1
while(onestep != twostep):
size += 1
onestep = onestep.next
return size
由于某种原因,我得到了奇怪的结果。每当尾部小于循环时,我都会得到正确的结果。但只要尾巴长于或等于循环的大小,我的函数就会获得更高的计数。
这里有一些例子:
Tail length = 1 Loop Length = 3
###result 3 - correct
Tail length = 999 Loop Length = 1000
###result 1000 - correct
Tail length = 1000 Loop Length = 999
###result 1998 - incorrect
Tail length = 50 Loop Length = 3
###result 51 - incorrect
Tail length = 3 Loop Length = 3
###result 6 - incorrect
Tail length = 3 Loop Length = 4
###result 4 - correct
【问题讨论】:
-
那么问题是什么?
标签: python loops linked-list singly-linked-list