传送门:环形链表 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:
mapping = []
p = head
while p:
if p not in mapping:
mapping.append(p)
else:
return p
p = p.next
return None
方法二:快慢指针
(图片来源于灵魂画师:@Julse(https://blog.csdn.net/Julse))
代码实现:
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
return None
if head is None or head.next is None:
return None
p = head # 第三个指针
slow = head.next
fast = head.next.next
while fast and fast.next:
if slow == fast:
while(p != slow):
p = p.next
slow = slow.next
return slow
slow = slow.next
fast = fast.next.next
return None