# 判断是否是环形链表
真题描述:给定一个链表,判断链表中是否有环。
示例 1:
输入:[3,2,0,4](链表结构如下图) 输出:true
解释:链表中存在一个环
解:
function hasCycle(head) {
while (head) {
if (head.flag) return true;
head.flag = true;
head = head.next;
}
return false;
}
# 定位环的起点
真题描述:给定一个链表,返回链表开始入环的第一个结点。 如果链表无环,则返回 null。
示例 1:
输入:head = [3,2,0,-4](如下图) 输出:tail connects to node index 1 解释:链表中有一个环,其尾部连接到第二个结点。
示例 2:
输入:head = [1,2](如下图)
输出:tail connects to node index 0
解释:链表中有一个环,其尾部连接到第一个结点。
示例 3:
输入:head = [1](如下图)
输出:no cycle
解释:链表中没有环。
解:
function detectCycle(head) {
while (head) {
if (head.flag) return head;
head.flag = true;
head = head.next;
}
return null;
}
使用快慢指针的解法:
function hasCycle(head) {
let slow = head, fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) {
return slow;
}
}
return null;
}
function detectCycle(head) {
const slow = hasCycle(head)
const fast = head;
while (fast && fast.next) {
fast = fast.next.next;
if (slow === fast) {
return slow;
}
}
return null;
}