[LeetCode] 141. Linked List Cycle 单链表判圆算法

TWO POINTER

快指针速度2 , 慢指针速度1

相对速度1,有环必然相遇

public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode fast = head,slow = head;
        while(fast!=null && fast.next!=null){
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast){
                return true;
            }
        }
        return false;
    }
}

猜你喜欢

转载自www.cnblogs.com/Poceer/p/10954550.html