-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlinked-list-cycle-ii.js
50 lines (45 loc) · 1.07 KB
/
linked-list-cycle-ii.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* Source: https://leetcode.com/problems/linked-list-cycle-ii/
* Tags: [Linked List,Two Pointers]
* Level: Medium
* Title: Linked List Cycle II
* Auther: @imcoddy
* Content: Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
*
*
*
* Follow up:
* Can you solve it without using extra space?
*/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
/**
* Memo: Mark val to NaN to indicate that this node has been visited.
* * The original list will be modified. and will fail if origianl list contains val of NaN
* Complex: O(n)
* Runtime: 140ms
* Tests: 16 test cases passed
* Rank: S
* Updated: 2015-06-20
*/
var detectCycle = function(head) {
while (head) {
if (isNaN(head.val)) {
return head;
} else {
head.val = NaN;
head = head.next;
}
}
return null;
};
//TODO add solution that doesn't change the orignal list