Leetcode-Linked List Cycle to determine whether a linked list has a ring

https://www.programcreek.com/2012/12/leetcode-linked-list-cycle/
Given a linked list, determine whether there is a ring in it.

analysis

If we have 2 pointers-fast and slow. If there is a circle, it can be guaranteed that fast people will meet slow people.

The following figure can illustrate the problem:
linked-list-cycle
Java Solution

public class Solution {
    
    
    public boolean hasCycle(ListNode head) {
    
    
        ListNode fast = head;
        ListNode 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 blog.csdn.net/abu935009066/article/details/112337396