> For the complete documentation index, see [llms.txt](https://rachel2011.gitbook.io/leetcode_cc150/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://rachel2011.gitbook.io/leetcode_cc150/linked-list/linked-list-cycle.md).

# Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Follow up:\
Can you solve it without using extra space?

第一种方法是使用set记录每次访问过的节点，若某节点被二次访问，则说明链表中有环。

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

第二种方法是使用two pointers。只需要判断链表是否有环。当链表没有环时是很好判断的，让一个指针一直往后走，遇见null了自然就没有环。而如何判断有环，那么就需要引入Faster和Slower的概念了（也是一种双指针方法）。顾名思义，同个时间Faster走的比Slower走的多。一般来说，Slower每次走一步，Faster每次走2步（通常这个概念可以判断链表中间点）。在这里，Faster和Slower同时从起点遍历链表，如果有环那么Slower和Faster肯定会相遇。

```
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        fast = slow = head

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

## 二刷

```
# 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
        """
        # head和head.next不存在
        if not head or not head.next:
            return False
        slow = head
        fast = head.next
        while fast != slow:
            # linkedlist到头了
            if not fast or not fast.next:
                return False
            fast = fast.next.next
            slow = slow.next
        return True
```
