LeetCode141. Circular linked list-fast and slow pointer

Title description

Given a linked list, determine whether there is a ring in the linked list.

If there is a node in the linked list that can be reached again by continuously tracking the next pointer, then there is a ring in the linked list. In order to represent the rings in a given linked list, we use the integer pos to indicate the position where the end of the linked list is connected to the linked list (the index starts from 0). If pos is -1, there are no rings in the linked list. Note: pos is not passed as a parameter, just to identify the actual situation of the linked list.

If there is a ring in the linked list, return true. Otherwise, it returns false.

Example 1:

Insert picture description here

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a ring in the linked list, and its tail is connected to the second node.

Example 2:
Insert picture description here

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a ring in the linked list, and its tail is connected to the first node.

Example 3:
Insert picture description here

Input: head = [1], pos = -1
Output: false
Explanation: There is no ring in the linked list

analysis

  1. About the pos parameter The
    topic gives a set of linked lists and a pos parameter. The function of the pos parameter is to explain whether the provided linked list has a ring or not. If there is no ring, pos=-1, so the pos parameter has little effect on our code writing and can be ignored.

  2. Detect whether there is a circular linked list.
    Use fast and slow pointers (refer to here, infringement deletion), that is, using the principle of tortoise and hare race, if you run infinitely in a circular playground, assuming that one side is fast enough, the two will inevitably be in different laps When meeting at the same place.
    The code is embodied as a pointer that moves fast and a pointer that moves slowly. If there is a loop, it will inevitably enter the race principle, otherwise there is no loop.

Code

public class Solution {
    
    

    public boolean hasCycle(ListNode head) {
    
    
        if(head == null || head.next == null){
    
    
            return false;
        }
        ListNode slow = head;
        ListNode quick = head.next;
        while (slow!=quick){
    
    
            if (quick == null || quick.next == null) return false;
            slow = slow.next;
            quick = quick.next.next;
        }
        return true;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43745087/article/details/114108807