python判断链表中是否有环

目录

  • 基本思路
  • 代码
  • 总结

题目链接: https://leetcode-cn.com/problems/linked-list-cycle/

基本思路

  利用快慢指针,快指针每次走两步,慢指针每次走一步。当慢==快时,说明存在环。若快指针变成了None,则说明无存在环。

代码

# 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 head == None:
            return False
        slow = head
        fast = head
        while fast:
            try:
                fast = fast.next.next
                slow = slow.next
            except:
                return False
            if fast == slow:
                return True

总结

a.主要勿忘记 head == None:的特殊情况。

你可能感兴趣的:(#,leetcode,指针,链表)