您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Linked List Cycle II

2015-08-30 21:17 513 查看

Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return
null
.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

https://leetcode.com/problems/linked-list-cycle-ii/

快慢指针。

https://leetcode.com/discuss/396/is-there-any-better-answer-for-the-linked-list-cycle-ii

两个指针重合说明有环。

然后把慢指针指向head,双指针每次走一步,再次重合就是结果。

/**
* @param {ListNode} head
* @return {ListNode}
*/
var detectCycle = function(head) {
var slow = head, fast = head;
while(true){
if(fast === null || fast.next === null){
return null;
}
slow = slow.next;
fast = fast.next.next;
if(slow === fast){
slow = head;
while(true){
if(slow === fast){
return slow;
}
slow = slow.next;
fast = fast.next;
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: