难度:中等
题目描述:
思路总结:这个和上次那个环形链表(判断是否有环)一样,看到之后想到用list或者hash存。但是这里把双指针又巧妙的利用上了。感概一句,双指针简直无所不能啊。分为两个阶段,具体思路看代码中的描述,这里就不多说了。
题解一:
# 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:
#思路:第一阶段,快慢指针相遇,距环头F个节点。2(F+b)~F+b;第二阶段,等速指针,相遇即环头
if not head or not head.next or not head.next.next:return
fast = head.next.next
slow = head.next
while fast != slow:
fast = fast.next.next
slow = slow.next
fast = head
while fast != slow:
fast = fast.next
slow = slow.next
return fast
题解一结果:
来源:CSDN
作者:LotusQ
链接:https://blog.csdn.net/qq_30057549/article/details/103726193