Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
由于最开始没有弄清楚链表中循环可以从任何位置开始,判断条件是是否tail的值等于head。但是这个题是判断一个链表中是否存在有环,因此这个循环的起始位置是未知的。所以改变了思路,采用两个指针,一个每次走一步,一个每次走两步。如果有回路存在,那么某个时刻两个指针相同。
Runtime: 48 ms
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None:
return False
else:
slow = head
fast = head
while fast.next!= None and fast.next.next != None:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
本文介绍了一种使用快慢指针的方法来判断链表中是否存在循环。通过一个每次前进一位的慢指针和一个每次前进两位的快指针,如果链表中有循环,则这两个指针最终会相遇。
309

被折叠的 条评论
为什么被折叠?



