链表是一种常用的的数据结构今天我们来讲讲一个链表如何判断它有环
其实思路就类似于龟兔赛跑围绕一个田径场 快的始终会与慢的相遇
我们创建两个指针一个叫fast一个叫slow 让fast一次移二步 slow一次移一步 当fast第一次=slow是说明有环返回true否则当fast=null或者fast.next=null时返回false
思路比较简单上代码:
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null||head.next==null){
return false;
}
ListNode slow=head.next;//慢指针
ListNode fast=head.next;//快指针
while(fast!=null&&fast.next!=null){
slow=slow.next;//走一步
fast=fast.next.next;//走两步
if(slow==fast){
return true;//第一次相遇返回true
}
}
return false;//当循环跳出返回false说明无环
}
}