自学内容网 自学内容网

python-leetcode-环形链表

141. 环形链表 - 力扣(LeetCode)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        if not head or not head.next:
            return False

        slow = head
        fast = head

        while fast and fast.next:
            slow = slow.next         # 慢指针走一步
            fast = fast.next.next    # 快指针走两步

            if slow == fast:         # 如果相遇,说明有环
                return True

        return False                # 如果快指针到达链表末尾,无环       


原文地址:https://blog.csdn.net/Lucy_wzw/article/details/145298184

免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!