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)
return false;
ListNode fast, slow;
fast = head.next;
slow = head;
while (fast != slow) {
if(fast==null || fast.next==null)
return false;
fast = fast.next.next;
slow = slow.next;
}
return true;
}