題目描述
給定一個鏈表,判斷鏈表中是否有環(huán)。
為了表示給定鏈表中的環(huán)对嚼,我們使用整數(shù) pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1俊马,則在該鏈表中沒有環(huán)。
示例 1:
輸入:head = [3,2,0,-4], pos = 1
輸出:true
解釋:鏈表中有一個環(huán)肩杈,其尾部連接到第二個節(jié)點(diǎn)柴我。
示例 2:
輸入:head = [1,2], pos = 0
輸出:true
解釋:鏈表中有一個環(huán),其尾部連接到第一個節(jié)點(diǎn)锋恬。
示例 3:
輸入:head = [1], pos = -1
輸出:false
解釋:鏈表中沒有環(huán)屯换。
進(jìn)階:
你能用 O(1)(即,常量)內(nèi)存解決此問題嗎与学?
Qiang的思路
# 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
"""
slow = head
fast = head
while fast != None and fast.next != None:
fast = fast.next.next
slow = slow.next
if slow == fast:
return True
return False if fast == None or fast.next == None else True