题目:
思路:快慢指针问题
代码:
# 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: fast = head slow = head while(fast!=None and fast.next!=None): #判断如果这个链表至少有两个节点,才可以形成环 fast = fast.next.next#快指针走一步 slow =slow.next#慢指针走一步 if(fast==slow):#如果他们相交,就返回True return True return False