題目描述
給定一個鏈表,判斷它是否有環。
樣例
給出 -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
複雜度分析
時間複雜度