题目描述
给定一个链表,判断它是否有环。
样例
给出 -21->10->4->5, tail connects to node index 1,返回 true
思路
快慢针。快针每次都两步,慢针每次走一步。如果无环,快针肯定会率先到达队尾,即遇到None。如果有环,快针永远无法遇到None,并且会与慢针相遇。
代码
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of the linked list.
@return: True if it has a cycle, or false
"""
def hasCycle(self, head):
# write your code here
if head is None:
return False
f = head
s = head
while f.next is not None and f.next.next is not None:
f = f.next.next
s = s.next
if s == f:
return True
return False
复杂度分析
时间复杂度 O(n) ,空间复杂度 O(1) 。