# Linked List Cycle

## Question

[leetcode: Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/)\
[lintcode: Linked List Cycle](http://www.lintcode.com/en/problem/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?
```

## 题解思路

链表中的Two Pointers是一种很常用的思想，快慢两个指针，通过是否相遇，来判断链表中是否有环。相比于用HashMap的方法，优点是空间复杂度仅为O(1)，时间复杂度O(n)。

参考 LeetCode: <https://leetcode.com/articles/linked-list-cycle/>

## 源代码

```java
/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != fast) {
            if (fast == null || fast.next == null) {
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://aaronice.gitbook.io/lintcode/linked_list/linked_list_cycle.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
