空間複雜度O(1): 快指針追上慢指針即可確定有迴環
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
l1 = head
l2 = head
while(l2 != None and l2.next != None):
l1 = l1.next
l2 = l2.next.next
if l1 == l2:
return True
return False
空間複雜度O(N):比較簡單,直接用哈希記錄即可