leetcode刷题5:找出链表中环的位置

来源:互联网 发布:d3.js 入门案例 编辑:程序博客网 时间:2024/05/02 09:48

和上个题类似:给定一个单链表,找出环开始的节点。

使用上一个题目的算法可以判断出当前链表有没有环。


观察1:

如果在快慢指针相遇后,我们继续向前移动慢指针,直到再次相遇,就可以计算出环的长度。

观察2:

使用一个指针遍历链表时,从环开始,经过环的长度次前进,指针会重新指向环开始的位置(从观察1可以很快得出)

观察3:

如果使用两个指针一前一后,假设环的长度为n,前面的指针前进n步之后,后面指针开始前进,则两个指针再次相遇的时候,就是环开始的位置。


综上,根据之前题目的算法可以得到代码:

class Solution:
    def detectCycle(self,head):
        if head == None:
            return None
        if head.next == None:
            return None
        if head.next == head:
            return head


        fast = head.next.next
        slow = head.next


        while fast != None and slow != None:
            if fast == slow:
                flag = True
                step = 1
                slow=slow.next
                while slow!=fast:
                    slow=slow.next
                    step +=1


                front=rear=head
                while step!=0:
                    step-=1
                    front=front.next


                while front!=rear:
                    front = front.next
                    rear = rear.next


                return front
                
                
            if fast.next == None:
                return None
            fast = fast.next.next
            slow = slow.next
        # if exist, won't pass through while loop at all.
            return None




0 0