题解 | #判断链表中是否有环#
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
判断指针是否有环:
- 指定两个指针,快指针和慢指针,快指针每次前进两步,慢指针每次前进一步,当快指针与慢指针相遇时有环,当快指针和慢指针不相遇时无环
- 边界条件,当输入为空时,默认无环
class Solution:
def hasCycle(self , head: ListNode) -> bool:
if head is None:
return False
fast = head
slow = head
while fast is not None and fast.next is not None:
print(fast.val)
fast = fast.next.next
slow = slow.next
if fast == slow:
return True
return False