您的位置:首页 > 其它

leetcode -- Linked List Cycle -- 重点

2015-12-09 20:46 405 查看
https://leetcode.com/problems/linked-list-cycle/

参考/article/4982512.html

一开始我错误的code:

class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""

if not head : return False
slow, fast = head, head

while fast and fast.next and fast != slow:#这里这个条件fast!=slow,使得在一开始就无法进入循环
slow = slow.next
fast = fast.next.next

if fast == None or fast.next == None:
return False
else:
return True


正确的code:

class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""

if not head : return False
slow, fast = head, head

while fast.next and fast.next.next:#这里用fast and fast.next也可以
slow = slow.next
fast = fast.next.next
if slow == fast:
return True

return False
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: