(head)
| 13 | |
| 14 | // 两个指针,一个一次走一步,一个一次走两步,如果有环会在某处相遇。 |
| 15 | var hasCycle = function(head) { |
| 16 | if (!head) { |
| 17 | return false |
| 18 | } |
| 19 | let oneIndex = head |
| 20 | let twoIndex = head.next |
| 21 | |
| 22 | if (!twoIndex) { |
| 23 | return false |
| 24 | } |
| 25 | |
| 26 | while (oneIndex && twoIndex) { |
| 27 | if (oneIndex === twoIndex) { |
| 28 | return true |
| 29 | } |
| 30 | |
| 31 | oneIndex = oneIndex.next |
| 32 | twoIndex = twoIndex.next |
| 33 | |
| 34 | if (!twoIndex || !twoIndex.next) { |
| 35 | return false |
| 36 | } |
| 37 | |
| 38 | twoIndex = twoIndex.next |
| 39 | } |
| 40 | |
| 41 | return false |
| 42 | }; |
nothing calls this directly
no outgoing calls
no test coverage detected