题目:
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
解法一
遍历链表,用map数据结构记录每次遍历的指针,若第一次发现有存在与map中的,这个指针指向的即是入口结点
function detectCycle(head){
var map=new Map();
while(head){
if(map.has(head)){
return head
}
map.set(head,head);
head=head.next;
}
return null
}
解法二
分两步:
1、快慢指针,快指针步幅2,慢指针步幅1,因为有环且一快一慢,所以一定会相遇,找到相遇点x,
2、将快指针重新指向头指针,步幅改为1,继续和慢指针一起遍历下去,此时速度相同,第一次相遇的时候的结点便是入口节点
// 快慢指针+数学分析
var detectCycle = function(head) {
if(head == null){
return null
}
var fast=head;
var low=head;
while(true){
if(fast.next != null && low.next != null){
if(fast.next.next == null){
return null
}
low=low.next;
fast=fast.next.next;
}else{
return null
}
if(fast === low){
break;
}
}
fast=head;
while(true){
if(fast === low){
break;
}
fast=fast.next;
low=low.next;
}
return low
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。