【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
};
相关推荐
共享家952729 分钟前
经典动态规划题解
算法·leetcode·动态规划
Pluchon29 分钟前
硅基计划3.0 Map类&Set类
java·开发语言·数据结构·算法·哈希算法·散列表
☼←安于亥时→❦1 小时前
PyTorch之张量创建与运算
人工智能·算法·机器学习
子豪-中国机器人2 小时前
枚举算法和排序算法能力测试
开发语言·c++·算法
qiuyunoqy2 小时前
基础算法之二分算法 --- 2
算法
1白天的黑夜12 小时前
栈-844.比较含退格的字符串-力扣(LeetCode)
c++·leetcode·
爱干饭的boy2 小时前
手写Spring底层机制的实现【初始化IOC容器+依赖注入+BeanPostProcesson机制+AOP】
java·数据结构·后端·算法·spring
二哈不在线2 小时前
代码随想录二刷之“动态规划”~GO
算法·golang·动态规划
cellurw3 小时前
俄罗斯方块终端游戏实现 —— C语言系统编程与终端控制
c语言·算法
诸葛务农4 小时前
光电对抗:多模/复合制导中算法和软件平台
算法