【LeetCode】【Study Notes】141. Ring Linked List

141. Circular Linked List

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

If there is a node in the linked list that can be nextreached again by continuously tracking the pointer, then there is a cycle in the linked list. In order to represent the ring in the given linked list, the evaluation system internally uses an integer posto indicate the position where the end of the linked list is connected to the linked list (the index starts from 0). Note: pos is not passed as a parameter . Just to identify the actual situation of the linked list.

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

Example 1:

img

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

Example 2:

img

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

Example 3:

img

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

hint:

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

problem solving ideas

speed pointer

Learning ideas: [LeetCode daily question] 141. Ring linked list | Handwritten graphic version of ideas + code explanation

Code

var hasCycle = function(head) {
    
    
    let fast=head;
    let slow=head;
    while(fast&&fast.next){
    
    
      slow=slow.next;
      fast=fast.next.next;
      if(slow==fast)return true
    }
    return false;
};

Guess you like

Origin blog.csdn.net/weixin_45944495/article/details/128323630