【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
};
相关推荐
黑屋里的马2 小时前
java的设计模式之桥接模式(Bridge)
java·算法·桥接模式
z187461030032 小时前
list(带头双向循环链表)
数据结构·c++·链表
sin_hielo2 小时前
leetcode 1611
算法·leetcode
李小白杂货铺2 小时前
识别和破除信息茧房
算法·信息茧房·识别信息茧房·破除信息茧房·算法推荐型茧房·观点过滤型茧房·茧房
来荔枝一大筐3 小时前
C++ LeetCode 力扣刷题 541. 反转字符串 II
c++·算法·leetcode
暴风鱼划水3 小时前
算法题(Python)数组篇 | 6.区间和
python·算法·数组·区间和
zl_vslam4 小时前
SLAM中的非线性优-3D图优化之轴角在Opencv-PNP中的应用(一)
前端·人工智能·算法·计算机视觉·slam se2 非线性优化
是苏浙4 小时前
零基础入门C语言之C语言实现数据结构之顺序表应用
c语言·数据结构·算法
lkbhua莱克瓦244 小时前
Java基础——常用算法3
java·数据结构·笔记·算法·github·排序算法·学习方法
小白程序员成长日记4 小时前
2025.11.07 力扣每日一题
数据结构·算法·leetcode