141.环形链表—力扣
Python3求解
# 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:
# 如果头结点为空,则无环返回
if not head: return False
# 设置两个指针,快慢指针,开始都指向头结点
fast=head
slow=head
# 当快指针或者快指针下一个节点非空时
while fast and fast.next:
# 快指针走两步,慢指针走一步
fast = fast.next.next
slow = slow.next
# 如果快慢指针相遇,证明有环
if fast == slow:
return True
# 循环退出,证明快指针走到空节点,证明无环
return False