【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
};
相关推荐
weixin_307779132 小时前
C++代码实现MATLAB中的dlarray函数功能
开发语言·c++·算法·matlab
hetao17338377 小时前
2026-10-03~04 hetao1733837 的刷题记录
c++·算法
Zootopia6268 小时前
飞行力学知识梳理1|飞行性能与稳定性
人工智能·python·算法·机器学习·无人机·学习方法·信息与通信
longlongzihan8 小时前
从LeetCode 70. 爬楼梯看动态规划:如何精准推导状态转移方程?
c++·算法·leetcode·动态规划
2601_960356389 小时前
2027校招采购岗解析:数学基础如何迁移到需求预测、成本与供应商分析
人工智能·算法
h_a_o777oah10 小时前
【树论】树链剖分:将树形结构转化为线性结构以处理树上路径问题(洛谷 P3384 附C++代码模板)
数据结构·算法·线段树·acm·树链剖分·树论·重链剖分
HEJOO910 小时前
指针的算术运算详解
java·数据结构·算法
Coder-magician10 小时前
《代码随想录》刷题打卡day47:并查集-part01
数据结构·算法·图论
垆边人似月.10 小时前
VLAN 资源池(100~200 分档)
数据结构·算法
潼心1412o11 小时前
C++初阶(长期更新)第6讲:类和对象(下)
开发语言·c++·算法