python----判断单链表是否有环

方法:快慢指针
#defination of a cycle listNode
class ListNode:
    def __init__(self,x):
        self.val=x
        self.next=None

class Solution:
    def ifCycleList(self,head):
        fast=head
        slow=head
        while fast and fast.next:
            slow=slow.next
            fast=fast.next.next
            if slow==fast:
                return True
        return False

if __name__=="__main__":
    head=ListNode(1)
    head.next=ListNode(2)
    head.next.next=ListNode(3)
    head.next.next.next=head
    su=Solution()
    print(su.ifCycleList(head))

二、找到环的入口点,方法:

当fast若与slow相遇时,slow肯定没有走遍历完链表,而fast已经在环内循环了n圈(1<=n)。假设slow走了s步,则 fast走了2s步(fast步数还等于s 加上在环上多转的n圈),设环长为r,则:

2s = s + nr s= nr

设整个链表长L,入口环与相遇点距离为x,起点到环入口点的距离为a。

a + x = nr

a + x = (n – 1)r +r = (n-1)r + L - a

a = (n-1)r + (L – a – x)

(L – a – x)为相遇点到环入口点的距离,由此可知,从链表头到环入口点等于(n-1)循环内环+相遇点到环入口点,于是我们从链表头、与相遇点分别设一个指针,每次各走一步,两个指针必定相遇,且相遇第一点为环入口点。

猜你喜欢

转载自blog.csdn.net/haoshan4783/article/details/88719050