public boolean hasCycle(ListNode head){
//1.使用快慢指针方式来判定
ListNode fast=head;
ListNode slow=head;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if(fast==slow){
return true;
}
}
return false;
}
给定一个链表,判断链表中是否有环
本文介绍了一种使用快慢指针来检测链表中是否存在环的高效算法。通过两个速度不同的指针遍历链表,如果存在环,快指针最终会追上慢指针。

被折叠的 条评论
为什么被折叠?



