1. 程式人生 > 實用技巧 >LeetCode 99. 恢復二叉搜尋樹 | Python

LeetCode 99. 恢復二叉搜尋樹 | Python

給定一個連結串列,判斷連結串列中是否有環。

為了表示給定連結串列中的環,我們使用整數 pos 來表示連結串列尾連線到連結串列中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該連結串列中沒有環。

示例 1:

輸入:head = [3,2,0,-4], pos = 1
輸出:true
解釋:連結串列中有一個環,其尾部連線到第二個節點。


示例2:

輸入:head = [1,2], pos = 0
輸出:true
解釋:連結串列中有一個環,其尾部連線到第一個節點。


示例 3:

輸入:head = [1], pos = -1
輸出:false
解釋:連結串列中沒有環。


來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/linked-list-cycle


越來越菜了,只會做做水題這樣子,,,

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        if not head or not head.next:
            return False
        slow=head
        fast=head.next
        while slow!=fast:
            if not fast or not fast.next:
                return False#無環,快指標先到尾部
            slow
=slow.next fast=fast.next.next return True