Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
算法思想:定义两个变量fast和slow,fast走过的路程是slow的两部,当fast回来和slow相遇时,证明有环,当出现fast的fast.next==null时说明没有环,结束判断。
public class LinkedListCycle {
public boolean hasCycle(ListNode head){
ListNode fast = head;
ListNode slow = head;
while (fast!=null)
{
slow = slow.next;
fast = fast.next;
if (fast!=null) fast = fast.next;
if (fast!=null && slow==fast) return true;
}
return false;
}
}