141.环形链表

给定一个链表,判断链表中是否有环。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
141.环形链表
141.环形链表

进阶:

你能用 O(1)(即,常量)内存解决此问题吗?

解1

  • 集合 x in set 时间复杂度为O(1)
  • 但空间复杂度为O(n)
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        
        s = set()
        
        if not head:
            return False
        
        cur = head
        s.add(cur)
        
        while cur.next is not None:
            
            if cur.next in s:
                return True
            else:
                s.add(cur.next)
                cur = cur.next
                
        return False

解2

双指针

  • 慢指针
  • 快指针
  • 若有环 则 慢指针 可以被 快指针 套圈
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        
        if not head:
            return False
        
        slow = head
        fast = head
        
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if fast == slow:
                return True
            
        return False