1. 程式人生 > >142. Linked List Cycle II(python)

142. Linked List Cycle II(python)

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
Subscribe to see which companies asked this question
題意:查詢環形連結串列的環的起點
思路:類似於141,快慢指標法可判斷環的存在與否
設頭結點到環的起點距離為a,環的起點到第一次相遇點距離為b,第一次相遇點到環的起點距離為c,則第一次相遇快指標走了(a+b+c+b),慢指標走了(a+b),快指標速度是慢指標的兩倍,則可得a=c。所以將快指標置於連結串列開頭,慢指標仍在相遇點,二者同時同速走,則相遇點就是環的起點
注意判斷兩指標是否相等,不是判斷兩指標的值是否相等
Runtime: 76 ms

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution(object):
    def detectCycle(self, head):
        dummy=ListNode(0)
        dummy.next=head
        slow=fast=dummy
        while fast.next and
fast.next.next: slow=slow.next fast=fast.next.next if slow==fast: fast=dummy while slow!=fast: slow=slow.next fast=fast.next return slow return None