- 我的思路:原地修改结点的next,将其指向自己,以此标记是否遍历过
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head or not head.next: return False # 特殊情况
ptr = head
while ptr:
pre = ptr
ptr = ptr.next
pre.next = pre # 将已经遍历过的结点的next指向自己
if ptr.next == None: return False # 最后一个指向None那就没有环
if ptr.next == ptr: # 最后一个指向(指向自己的结点)那就有环
return True
return False
- 快慢指针
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head or not head.next: 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
- 用额外空间集合标记遍历与否
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
sets = set()
while head:
if head in sets: return True
sets.add(head)
head = head.next
return False
就很奇怪…T^T
参考链接:官方解析