141LeetCode141 circular list is implemented using fast and slow pointers

LeetCode141 ring list

LeetCode141 ring list

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, 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, then there is no ring 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.

Advanced:

Can you solve this problem with O(1) (ie, constant) memory?

Example 1 :
Insert picture description here

输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:

Example 2:

Insert picture description here

输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。

Example 3:

Insert picture description here

输入:head = [1], pos = -1
输出:false
解释:链表中没有环。

prompt:

The range of the number of nodes in the linked list is [0, 104]
-105 <= Node.val <= 105
pos is -1 or a valid index in the linked list.

Problem-solving ideas

Use the fast and slow pointer to solve the problem
**
What is the fast and slow pointer:

For example, there is a while() loop. There is a slow pointer and a fast pointer. The slow pointer moves one space at a time, and the fast pointer moves two pointers at a time. This is like if two people are running on the playground. Because the playground is round, the fast runner will meet the slow runner at a certain moment. The playground is like a ring. If the modified linked list is a circular linked list, it means that the fast pointer and the slow pointer will meet at a certain moment. If there is no ring in the linked list, fast will point to a null

Insert picture description here

**Source: **Little Ma Ge Education

Insert picture description here

Code

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

Guess you like

Origin blog.csdn.net/pjh88/article/details/114378350