Leetcode – Linked List Cycle判断一个链表是否有环

367 阅读1分钟

www.programcreek.com/2012/12/lee…
给定一个链表,确定其中是否有环。

分析

如果我们有2个指针-快和慢。如果存在一个圆,可以保证快的人会遇到慢的人。

下图可以演示该问题:
linked-list-cycle
Java Solution

public class Solution {
    public boolean hasCycle(ListNode head) {
        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;
    }
}