LeetCode Brushing Notes _141. Circular Linked List

The topic is from LeetCode

141. Circular Linked List

Other solutions or source code can be accessed: tongji4m3

description

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

If there is a node in the linked list, which 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.

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

prompt:

链表中节点的数目范围是 [0, 104]
-105 <= Node.val <= 105
pos 为 -1 或者链表中的一个 有效索引 。

Code

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

Guess you like

Origin blog.csdn.net/weixin_42249196/article/details/108634877