给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
说明:不允许修改给定的链表。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:tail connects to node index 1
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0
输出:tail connects to node index 0
解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1
输出:no cycle
解释:链表中没有环。
1. 解法:一般遇到这种链表类题目都是用快慢指针的来解决的。循环链表 1 很简单,直接龟兔赛跑或者哈希表就完事了。然而,循环链表 2 需要给出相遇的位置,这里用到了数学相关的东西,证明的部分我们就不看了。大致的思想就是这个样子。首先我们设定 slow 和 fast 两个快慢指针,开始均指向 head。然而开始遍历,遍历到第一次 head 与 fast 相遇的地方,然后把 fast 指向 head,这里记住要调整快指针的步数与慢指针的步数(均为一),然后快慢指针重合的地方,这个时候就是入环的地方。
/**
* 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 === null || head.next === null) return null;
let slow = head, fast = head;
while(fast !== null && fast.next !== null) {
fast = fast.next.next;
slow = slow.next;
if(fast === slow) {
fast = head;
while(slow !== fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
};