双指针:leetcode142(中等)——环形链表2

题目

双指针:leetcode142(中等)——环形链表2

题解

思路:floyd判圈法;

# 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 True:
                    if not (fast and fast.next):
                        return
                    fast = fast.next.next
                    slow = slow.next
                    if fast == slow:
                        break
                fast = head
                while fast != slow:
                    fast = fast.next
                    slow = slow.next
                return fast
上一篇:力扣287——寻找重复数(快慢指针)


下一篇:LeetCode 234.回文链表(快慢指针+反转单链表)