public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head;
while(head!=null&&head.next!=null&&head.next.next!=null){
head=head.next.next;
slow = slow.next;
if (head==slow) return true;
}
return false;
}
}
判断链表是否有环
该博客讨论了一种检查链表中是否存在环的算法。通过使用快慢指针,当快指针到达链表末尾或者遇到环时,慢指针刚好在环内,从而有效地确定链表是否有环。这种方法避免了冗余遍历,提高了效率。

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



