链表有环判断:快慢指针相遇
判断链表中是否有环
http://www.nowcoder.com/questionTerminal/650474f313294468a4ded3ce0f7898b9
快指针每次两步,慢指针每次一步,有环则必相遇。
终止条件:null,单个节点,两个结点,都不可能有环!
public boolean hasCycle(ListNode head) {
if(head==null||head.next==null||head.next.next==null){
return false;
}
ListNode fast=head;
ListNode slow=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow){
return true;
}
}
return false;
}

