public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null||head.next==null)
return false;
ListNode fast=head.next;
ListNode slow=head;
while(fast!=slow){
if(fast==null||fast.next==null)
return false;
fast=fast.next.next;
slow=slow.next;
}
return true;
}
}
快慢指针
本文介绍了一种使用快慢两个指针来判断链表中是否存在环的方法。通过不断迭代,快指针每次移动两步,慢指针每次移动一步,如果两者相遇则表明链表中有环。
525

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



