141.双向链表(javascript)141.LinkedListCycle

原创
小哥 3年前 (2022-11-10) 阅读数 5 #大杂烩

leetcode: https://leetcode-cn.com/problems/linked-list-cycle/

为您提供链接列表的头节点 head ,确定列表中是否有环。

如果列表中有一个节点,则可以对其进行连续跟踪。 next 如果指针再次到达,列表中会出现一个环。 为了表示给定列表中的环,计算系统在内部使用整数。 pos 表示列表末尾连接到列表的位置(索引来自)。 0 开始)。注:pos 未作为参数传递 。只是为了确定列表的实际情况。

如果链表中有戒指 ,则返回 true 。 否则,返回 false 。

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.

示例 1:

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

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).

示例 2:

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

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.

示例 3:
输入:head = [1], pos = -1
输出:false
说明:列表中没有戒指。

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

解题方法1:
使用快速和慢速指针,fast && fast.next对于空处理,
slow 为慢指针
fast 为快指针

每个周期,慢指针走一步,快指针走两步,
第一:链表中没有环,两个指针不会相遇,指针很快就会到头。
第二种类型:链表中有环,两个指针会相遇(注意:首先判断它们是否相遇)

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

解题方法2:
1.创建一个map集合,循环列表,当访问的节点在时。map当它存在时,证明它以前就存在过,这意味着链表中有环。
2.当受访节点处于map如果不存在,请添加。map,节点向下一步
3.循环结束时,表示列表中没有循环。

var hasCycle = function(head) {
    let h=new Map()
    while(head){
        if(h.has(head)) return true
        h.set(head)
        head=head.next
    }
    return false
};
版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除