【leetcode】141.环形链表

阅读 50

2022-03-10

题目

【leetcode】141.环形链表
判断链表是否有环

解法

快慢指针

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

精彩评论(0)

0 0 举报