js_algorithm
js_algorithm copied to clipboard
环形链表 II
leetcode: https://leetcode-cn.com/problems/linked-list-cycle-ii/
题目分析
本道题目和之前的这道很相似。不同之处在于这里返回的是链表开始入环的第一个节点。
在之前的基础上稍加改造就可以。
编码实现
/**
* 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
};