Cosen95 / js_algorithm

🏂js数据结构与算法 系统学习
36 stars 10 forks source link

环形链表 II #21

Open Cosen95 opened 4 years ago

Cosen95 commented 4 years ago

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

Cosen95 commented 4 years ago

题目分析

本道题目和之前的这道很相似。不同之处在于这里返回的是链表开始入环的第一个节点。

在之前的基础上稍加改造就可以。

编码实现

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var detectCycle = function(head) {
    while (head) {
        if(head.flag) {
            return head
        } else {
            head.flag = true;
            head = head.next;
        }
    }
    return null
};