题目描述:
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 next2=head;
while(head!=null&&next2!=null&&next2.next!=null){
head=head.next;
next2=next2.next.next;
if(head==next2){
return true;
}
}
return false;
}