F cycle detection判圈算法,是一个可以在有限状态机、迭代函数或者链表上判断是否存在环,求出该环的起点与长度的算法。
题目 | 简介 |
---|---|
141. Linked List Cycle | 判断链表是否有环 |
142. Linked List Cycle II | 找到环的起始点 |
287. Find the Duplicate Number | 迭代函数 |
202. Happy Number | 迭代函数 |
141. Linked List Cycle
龟兔赛跑,若赶得上就是有环。
注意fast每次走两步,fast = fast.next.next,则在while-loop条件中的fast.next != null就必须加,否则test case:[1], -1这个单个node的就会fail。
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast = head, slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
return true;}
}
return false;
}
}