给你一个链表的头节点 head ,判断链表中是否有环。

如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos 不作为参数进行传递 。仅仅是为了标识链表的实际情况。

如果链表中存在环 ,则返回 true 。 否则,返回 false 。

示例


输入:head = [3,2,0,-4], pos = 1

输出:true

解释:链表中有一个环,其尾部连接到第二个节点。

解析

1)链表中如果有环,则一定会出现重复元素,所以可以用哈希表存储已遍历的节点,边遍历边对比;

2)另一种解法,就是用快慢指针,慢的每次走一步,快的每次走两步;

3)当链表中不存在环时,快指针将先于慢指针到达链表尾部,链表中每个节点至多被访问两次;

4)当链表中存在环时,每一轮移动后,快慢指针的距离将减小一,至多N次就能相遇。

代码示例

1、哈希存储法

# 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:
        seen = set()
        while head:
            if head in seen:
                return True
            seen.add(head)
            head = head.next
        return False

2、快慢指针法

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

        slow, fast = head, head
        fast = fast.next

        while fast and fast.next:
            if fast == slow:
                return True
            fast = fast.next.next
            slow = slow.next
        return False

执行用时:52 ms, 在所有 Python3 提交中击败了 90.93% 的用户.

本文为 陈华 原创,欢迎转载,但请注明出处:http://www.ichenhua.cn/read/382