# 空煉表和空樹都要預防
return
false
ls =
cur = head.
next
while cur and
(cur not
in ls)
: cur = cur.
next
ifnot cur:
# 當沒有環時
return
false
return
true
# 存在環時
# definition for singly-linked list.
# class listnode:
# def __init__(self, x):
# self.val = x
# self.next = none
class
solution
:def
hascycle
(self, head: listnode)
->
bool
:# 使用快慢指標法
ifnot head:
# 先解決空鍊錶的情況
return
false
slow = head
fast = head
while fast and fast.
next
:# 速度不一,間距一直在縮小,有環則兩者相遇,沒環,提前結束
slow = slow.
next
# 以乙個結點為步長
fast = fast.
next
.next
# 以兩個結點為步長
if slow == fast:
return
true
return
false
141 環形鍊錶
給定乙個鍊錶,判斷鍊錶中是否有環。高階 你能否不使用額外空間解決此題?乙個快指標走兩步 乙個慢指標走一步 如果相遇就有環 不然沒環 class solution def hascycle self,head type head listnode rtype bool index1 head inde...
141 環形鍊錶
鏈結 給定乙個鍊錶,判斷鍊錶中是否有環。為了表示給定鍊錶中的環,我們使用整數 pos 來表示鍊錶尾連線到鍊錶中的位置 索引從 0 開始 如果 pos 是 1,則在該鍊錶中沒有環。示例1輸入 head 3,2,0,4 pos 1 輸出 true 解釋 鍊錶中有乙個環,其尾部連線到第二個節點。示例2 輸...
141 環形鍊錶
給定乙個鍊錶,判斷鍊錶中是否有環。為了表示給定鍊錶中的環,我們使用整數 pos 來表示鍊錶尾連線到鍊錶中的位置 索引從 0 開始 如果 pos 是 1,則在該鍊錶中沒有環。示例 1 輸入 head 3,2,0,4 pos 1 輸出 true 解釋 鍊錶中有乙個環,其尾部連線到第二個節點。1.首先想到...