https://www.programcreek.com/2012/12/leetcode-linked-list-cycle/
给定一个链表,确定其中是否有环。
分析
如果我们有2个指针-快和慢。如果存在一个圆,可以保证快的人会遇到慢的人。
下图可以演示该问题:
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;
}
}