142. 环形链表 II
题目描述
代码实现
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
# 快慢指针
fast, slow = head, head
while fast and fast.next:
fast, slow = fast.next.next, slow.next
if fast == slow:
fast = head
while fast != slow:
fast, slow = fast.next, slow.next
return fast
return None
def detectCycle2(self, head: ListNode) -> ListNode:
# 哈希表解法
if not head:
return None
hashSet = set()
while head:
if head in hashSet:
return head
hashSet.add(head)
head = head.next
return None