Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
使用两个指针,一个指针每次直走一步,另一个指针每次走两步,如果是链表有环,那么两个指针总会相遇,否则快指针访问到链表尾部就结束。
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) return false;
ListNode fast = head;
while (head != null&&fast!=null&&fast.next!=null) {
fast = fast.next.next;
head = head.next;
if (fast==head) return true;
}
return false;
}