原题:https://oj.leetcode.com/problems/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?
思路:创建两个指针,一快一慢,如果两个指针在某一时刻能重合,说明有环(如果有环,必存在一个最小公倍数,让两者迟早可以重合;如果无环,链表结尾必为null)
AC代码:
public class LinkedListCycle {
public boolean hasCycle(ListNode head) {
if(head == null) return false;
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
if(fast == slow) {
return true;
}
}
return false;
}
}