1. 程式人生 > >leetcode141. 環形連結串列 & 142 環形連結串列 II

leetcode141. 環形連結串列 & 142 環形連結串列 II

def hasCycle(self, head):
        """
        注意邊界越界的問題
        設定一個快指標和慢指標,慢指標和快指標相遇就存在環,如果有存在節點的next為None的情況沒有環。
        """
        if not head:
            return False
        if not head.next or not head.next.next:
            return False
        s = head.next
        f = head.next.next
        while f and s:
            if f == s:
                return True
            elif not f.next or not s.next:###邊界越界
                return False
            else:
                s = s.next
                f = f.next.next
                
        return False

leetcode 142

def detectCycle(self, head):
        """
        在141基礎上先判斷是否存在環(快慢指標)
        如果存在環,繼續把快指標=head,快指標走一步,繼續走下去,直到相遇點就是環的入口點
        """
        if not head:
            return None
        if not head.next or not head.next.next:
            return None
        s = head.next
        f = head.next.next
        flag = 0
        while f and s:
            if f == s:
                break
            elif not f.next or not s.next:###邊界越界
                return None
            else:
                s = s.next
                f = f.next.next
        '''
        邊界條件注意
        '''
        if s == f and f.next:
            f = head
            while f != s:
                s = s.next
                f = f.next
            return f
            
        return None

為什麼是快指標是慢指標的兩倍速度,為什麼入口點是相遇之後放慢快指標再次相遇的點,參考

https://blog.csdn.net/xy010902100449/article/details/48995255