[LeetCode] 141. Linked List Cycle singly linked list algorithm sentenced round

TWO POINTER

2 pointer speed faster, slower pointer speed 1

1 relative velocity, there will inevitably encounter ring

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;
    }
}

 

Guess you like

Origin www.cnblogs.com/Poceer/p/10954550.html