Niuke.com Brushing Questions-Determine whether there is a ring in the linked list

Problem Description

Determine whether there is a ring in the given linked list. If there is a loop, it returns true, otherwise it returns false.

Input description:
Input a linked list

Output description:
Does the output linked list contain rings?

Example

Example 1

Enter
1->2->3

Output
false

Solutions

analysis

  1. By means of fast and slow pointers, one pointer passes one node at a time, and the other pointer passes two nodes at a time. When the fast node catches up to full nodes, it means that it contains a ring structure.

method

  1. Judge by means of fast and slow pointers (tortoise and hare race: the picture uses the picture of the force button)
    Insert picture description here

Code

// 思路1
public class Solution {
    
    
    if (head == null || head.next == null) {
    
    
        return false;
    }

    ListNode slow = head;
    ListNode fast = head.next;

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

        slow = slow.next;
        fast = fast.next.next;
    }

    return false;
}

If you want to test, you can go directly to the link of Niuke.com to do the test

Determine whether there is a ring in the linked list

Guess you like

Origin blog.csdn.net/qq_35398517/article/details/113125231