Determine whether the linked list has a cycle through the fast and slow pointer

Get into the habit of writing together! This is the 15th day of my participation in the "Nuggets Daily New Plan·April Update Challenge", click to view the details of the event .

Topic description

Given the head node of a linked list head, determine whether there is a cycle in the linked list.

If there is a node in the linked list that can be reached again by continuously tracing the nextpointer , then there is a cycle in the linked list. In order to represent a cycle in a given linked list, the evaluation system internally uses an integer posto indicate the position in the linked list where the tail of the linked list is connected (the index starts from 0). Note: posNot passed as a parameter  . Just to identify what the linked list actually is.

 Returns if there is a cycle in the linked listtrue . Otherwise, return false.

Example

image.png

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

image.png

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

image.png

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

hint

  • The range of the number of nodes in the linked list is [ 0,10 4 ^4
  • -10 5 ^5  <= Node.val <= 10 5 ^5
  • pos is  -1 a  valid index in the or linked list  .

double pointer

To determine whether a linked list has a ring, we can define the fast and slow pointers and find the node that forms the ring by moving the pointers.

step:

  1. Boundary judgment
  2. Define the fast and slow pointer, the fast pointer moves two spaces at a time, and the slow pointer moves one at a time
  3. Keep looping until the fast pointer is empty or the node forming the ring is found
  4. return result

1.gif

2.gif

public class Solution {
    public 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 juejin.im/post/7086790088327168007