# 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
"""
# 1.用set
a = set()
while head:
if head in a:
return True
a.add(head)
head = head.next
return False
# 2.用快慢指针
if head is None or head.next is None or head.next.next is None:
return False
slow = head
fast = head.next
while slow != fast:
if not fast or not fast.next:
return False
slow = slow.next
fast = fast.next.next
return True
70-双指针--LC141环形链表
最新推荐文章于 2024-08-30 11:06:53 发布