判断链表是否有环

# 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 
        fast = slow = head
        while fast:
            if fast.next and fast.next.next:
                fast = fast.next.next
                slow = slow.next
            else:
                return False
            
            if fast == slow:
                return True
        
posted @ 2021-03-08 15:26  KbMan  阅读(37)  评论(0编辑  收藏  举报