题目
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){
ListNode slow=head,fast=head;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if(fast==slow)
return true;
}
return false;
}
本文介绍了一种使用快慢指针来判断链表是否存在环的经典算法。通过设置一个每次前进一步的慢指针和一个每次前进两步的快指针,在不额外占用空间的情况下高效地检测出链表中是否包含环。
832

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



