---
title: "Linked List Cycle"
author: "KickCode"
date: "2016-02-13T03:11:51Z"
tags: []
categories: ["编程语言"]
slug: "linked-list-cycle"
draft: false
lastmod: "2016-02-13T03:11:51Z"
id: 2276248
url: "https://kickcode.iteye.com/blog/2276248"
---

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

判断一个链表中是否有环存在，用快慢指针来解决，设定两个指针fast和slow都指向head，我们让fast = fast.next.next，slow = slow.next，如果存在环，fast和slow就会相遇，因此当fast == slow时我们就返回true, 否则返回false。代码如下：

```java

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null || head.next == null) return false;
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast)
                return true;
        }
        return false;
    }
}

```