关于Leetcode问题”;“链表循环”python

关于Leetcode问题”;“链表循环”python,python,Python,我没有回答这个问题。 问题是 答案是 head = [3,2,0,-4] pos = 1 class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def hasCycle(self, head): if head is None: return False f

我没有回答这个问题。 问题是

答案是

head = [3,2,0,-4]
pos = 1

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def hasCycle(self, head):
        if head is None:
            return False
        
        fast = head.next
        slow = head
        
        while slow is not None:
            if fast is None or fast.next is None:
                return False
            
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                return True
            
        return False
            
s = Solution()
print(s.hasCycle(head))
我在VScode终端上运行它,但是 错误发生了

Traceback (most recent call last):
  File "LinkedListCycle.py", line 30, in <module>
    print(s.hasCycle(head))
  File "LinkedListCycle.py", line 15, in hasCycle
    fast = head.next
AttributeError: 'list' object has no attribute 'next'
回溯(最近一次呼叫最后一次):
文件“LinkedListCycle.py”,第30行,在
打印(s.hasCycle(头))
文件“LinkedListCycle.py”,第15行,在hasCycle中
快=头。下一个
AttributeError:“list”对象没有属性“next”
我不知道“列表”对象是什么。
为什么会出现这种情况?

因为您的
头=[3,2,0,-4]
是数组,在python中称为list。而list对象在python中没有next属性。

您需要首先从
列表
值创建一个链表

def make_ll(lst):
    if not lst:
        return None
    ll = ListNode(lst[0])
    ll.next = make_ll(lst[1:])
    return ll

s = Solution()
print(s.hasCycle(make_ll(head)))

您可以这样设置问题:

lst, pos = [3,2,0,-4], 1

node = tail = None
for i, val in reversed(list(enumerate(lst))):
    head = ListNode(val)
    if tail is None:
        tail = head
    if i == pos:
        tail.next = head
    head.next = node
    node = head

# head is now a linked list with a cycle starting at index pos

与类似的建议方法不同,这纯粹是迭代和线性的。它还将最后一个节点链接到循环开始位置的节点。

在运行时,Leetcode将只为您提供一个ListNode(链的头部),解释中包含的列表只是描述链内容的一种方式。它们不是您应该用于测试的。您需要根据这些列表构建自己的ListNodes链来执行测试:

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

values,pos = [3,2,0,-4],1
nodes  = [ListNode(v) for v in values]
for node,nextNode in zip(nodes,nodes[1:]+nodes[pos:pos+1]):
    node.next = nextNode
head   = nodes[0]
现在,您可以使用head测试您的解决方案:

Solution().hasCycle(head)
作为旁注,当您快速前进时,您应该检查两个步骤的慢速和快速之间是否相等。否则,您可能会跳过缓慢的迭代器,如果循环中有偶数个节点,则可能永远无法到达它

O(n)时间和O(1)空间中的示例:


head
被声明为python
list
并且它没有属性
next
。提示:您甚至没有使用过
ListNode
类一次……提示2:
head
应该是
ListNode
“'list'对象”是
[3,2,0,-4]
,它不是链表。您需要先创建一个链表。(而且
解决方案
类是毫无意义的-你只需要函数。你不需要用Python进行对象痴迷的编程。)@molbdnilo我记得
解决方案
类是LeetCode强加的要求。
def hasCycle(head):
    tail = head and head.next           # cover case of no list at all  
    step = 1
    while tail and head is not tail:    # check at every step
        if step%3 : tail = tail.next    # advance tail twice as often
        else      : head = head.next
        step += 1
    return bool(tail) # cycle present when tail has not reached end