问题形如:链表中存在环,找到第一个节点,或者找到倒数第k个节点,或者找到中间的节点;都是要设置多个指针同时遍历,指针遍历的述律满足一定的条件,这样子来解决问题
var detectCycle = function(head) {
let fast = head;
let slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
let slow2 = head;
while(slow2 != slow){
slow = slow.next;
slow2 = slow2.next;
}
return slow;
}
}
return null;
};
本文介绍了一种使用快慢指针技术检测链表中是否存在环的高效算法,并详细解释了如何定位到环的起始节点。通过双指针以不同速度遍历链表,当两指针相遇时,则说明链表存在环。
14万+

被折叠的 条评论
为什么被折叠?



