LeeCode141 circular linked list (Java) (fast or slow pointer or simple thinking)

Topic link: LeeCode141 circular linked list
Topic description: Insert picture description here
First of all, when you get the question, you should judge whether the current point has been before. If you have not, then go. If you come to the point you have come again, it ends, but this one has never come. It is not very good to make a perfect judgment when changing the nodes of the linked list. But the question is over

public static boolean hasCycle(ListNode head) {
    
    
        List<Integer> list=new ArrayList<>();
        while(head!=null){
    
    
            if(head.val==Integer.MIN_VALUE)return true;
            head.val=Integer.MIN_VALUE;
            head=head.next;
        }
        return false;
    }

Then I always felt that the judgment was not perfect, so I looked for a solution, so I wrote one with a quick and slow pointer. The idea is quite simple, but I didn't expect to start setting two pointers, one at the head node and one at the head node. After the head node, one moves one step at a time, and one moves two steps at a time. If there is a loop, the two pointers will coincide at a certain moment, and if there is no loop, they will never coincide.

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

Guess you like

Origin blog.csdn.net/weixin_43590593/article/details/113060660