Niuke Baidu algorithm problem (simple)-determine whether the linked list has a ring (requires space complexity O (1))

Title :

Determine whether there is a ring in the given linked list. If there is a loop, it returns true, otherwise it returns false.
Can you give a solution with space complexity O(1)?

Insert picture description here

Input
none

Output
none

Ideas:

Fast and slow pointer judgment method : Set two pointers, starting from the same starting point, one has a speed of 2 nodes/time, and the other has a speed of 1 node/time,
if there is no ring in this linked list. Then the slow pointer can never catch up with the fast pointer until the fast pointer traverses to NULL first, exits the loop, judges the end, and outputs false.
If there is a ring in this linked list, then the slow pointer and the fast pointer will always move around the ring, and at some point It must overlap, the judgment is over at this time, and the output is true

Why must we meet? ? , We assume that the length of the loop is L (L>=2) the
fast pointer speed is 2, the slow pointer speed is 1, set the movement time to t, O is the reference starting point, the
slow pointer point is M, the fast pointer point is F, assuming the initial displacement oF = x1, OM = x2, the clockwise direction is positive
then after a time t, = fast pointer. oF (X1 + 2 * t)% L
after the elapsed time t, = slow pointer OM (t + X2)% L
that Is there t such that (2 * t + x1)% L = (t + x2)% L ?
That is to say whether (2 * t + x1) three (t + x2) mod L has a real number solution t
This formula is equivalent to : (2 * t + x1-(t + x2)) mod L = 0 (If you don’t understand this formula, go to see the definition of the modulus)
Simplify: (t + x1-x2) mod L = 0
must be Solution, fools know that there is a solution! ! !
So the fast and slow pointers will definitely meet, so you only need to judge whether the fast and slow pointers meet to know whether the linked list has a ring;
Insert picture description here

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    
    
    public boolean hasCycle(ListNode head) {
    
    
        ListNode f = head;
        ListNode m = head;
        while(f!=null && f.next!=null){
    
    
            f = f.next.next;
            m = m.next;
            if(f==m) return true;
        }
        return false;
    }
}

Guess you like

Origin blog.csdn.net/YSJ367635984/article/details/113247081