# 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:
fast,slow = head,head
# 注意這里的條件,一定要slow,fast,寫在前面,
while slow and fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
return True
else:return False
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/164758.html
標籤:Python
下一篇:Python實作通用web框架
