找到环形链表的第一个节点
- 时间复杂度O(n),空间复杂度O(1)
- Runtime: 88 ms, faster than 60.79%
- Memory Usage: 41.5 MB, less than 69.61%
快慢指针,快指针到达节点后,慢指针指向头节点,然后一起走,相等的节点就是环形链表的第一个交点。
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var detectCycle = function(head) {
if (!head || !head.next) return null;
let slow = head.next;
let fast = head.next.next;
while (slow !== fast) {
if (!fast || !fast.next) return null;
slow = slow.next;
fast = fast.next.next;
}
slow = head;
while (slow !== fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
};
网友评论