【LeetCode 0141】【链表】【双指针之快慢指针】判断给定单链表是否存在环

  1. Linked List Cycle

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

Return true* if there is a cycle in the linked list*. Otherwise, return false.

Example 1:

复制代码
**Input:** head = [3,2,0,-4], pos = 1
**Output:** true
**Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

Example 2:

复制代码
**Input:** head = [1,2], pos = 0
**Output:** true
**Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node.

Example 3:

复制代码
**Input:** head = [1], pos = -1
**Output:** false
**Explanation:** There is no cycle in the linked list.

Constraints:

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

Follow up: Can you solve it using O(1) (i.e. constant) memory?

Idea
text 复制代码
* 如果链表不存在环,则迭代会遍历终止(末尾节点为null)
* 如果存在环,则有且只有一个环,而且只能是在链表尾部形成环
  类似龟兔赛跑,慢指针迟早会赶上快指针,如果存在快指针于慢指针重叠,则说明存在环。
JavaScript Solution
javascript 复制代码
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} head
 * @return {boolean}
 */
var hasCycle = function(head) {
    if(!head){
        return false
    }
    let [slow,fast] = [head,head.next]
    while(fast && fast.next){
        if(slow==fast){
            return true
        }
        slow = slow.next
        fast = fast.next.next
    }
    return false
};
相关推荐
JAVA学习通10 分钟前
JDK高版本特性总结与ZGC实践
java·jvm·算法
syty202013 分钟前
简简单单区块链
算法·哈希算法
CoovallyAIHub17 分钟前
CLIP, DINO等多模型融合DreamSim,让电脑“看懂”图片有多像!模型融合成为热门!
深度学习·算法·计算机视觉
Giser探索家24 分钟前
遥感卫星升轨 / 降轨技术解析:对图像光照、对比度的影响及工程化应用
大数据·人工智能·算法·安全·计算机视觉·分类
仰泳的熊猫28 分钟前
LeetCode:700. 二叉搜索树中的搜索
数据结构·c++·算法·leetcode
嵌入式-老费29 分钟前
Easyx图形库应用(图形旋转)
算法
代码充电宝35 分钟前
LeetCode 算法题【中等】189. 轮转数组
java·算法·leetcode·职场和发展·数组
微笑尅乐1 小时前
从递归到迭代吃透树的层次——力扣104.二叉树的最大深度
算法·leetcode·职场和发展
im_AMBER1 小时前
Leetcode 28
算法·leetcode
让我们一起加油好吗2 小时前
【基础算法】多源 BFS
c++·算法·bfs·宽度优先·多源bfs