Likou 141 circular linked watch (hash watch + speed pointer)

1. Title

Insert picture description here

2. My initial thoughts and problems

Remember the method of hash table or fast and slow pointer.
When solving the problem with the hash table method, pay attention to the logic. The !set.add(temp) statement is executed to add temp to the set and return a boolean value.

3. Problem solving method 1: hash table

public class Solution {
    
    
    public boolean hasCycle(ListNode head) {
    
    
        Set<ListNode> set = new HashSet<>();
        ListNode temp = head;
        while(temp != null){
    
    
            if(!set.add(temp)){
    
    
                return true;
            }
            temp = temp.next;
        }
        return false;
    }
}

Insert picture description here

4. Problem solving method two: quick and slow pointer

public class Solution {
    
    
    public boolean hasCycle(ListNode head) {
    
    
        if(head == null || head.next == null){
    
    
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;

        while(slow != fast){
    
    
            if(fast == null || fast.next == null){
    
    
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;

    }
}

Just write it out.
It should be noted here that, first determine whether head and head.next are null,
and then determine whether fast and fast.next are empty after defining fast . This step cannot be ignored.

Insert picture description here

Guess you like

Origin blog.csdn.net/ambitionLlll/article/details/113921136