MCPcopy Create free account
hub / github.com/douchuan/algorithm / has_cycle

Function has_cycle

src/ll/cycle.rs:11–27  ·  view source on GitHub ↗

使用双指针,一个指针每次移动一个节点,一个指针每次移动两个节点, 如果存在环,那么这两个指针一定会相遇。

(p: Option<NonNull<Node<T>>>)

Source from the content-addressed store, hash-verified

9/// 使用双指针,一个指针每次移动一个节点,一个指针每次移动两个节点,
10/// 如果存在环,那么这两个指针一定会相遇。
11fn has_cycle<T>(p: Option<NonNull<Node<T>>>) -> bool {
12 let mut fast = p;
13 let mut slow = p;
14
15 loop {
16 unsafe {
17 fast = fast.and_then(|v| v.as_ref().next.and_then(|next| next.as_ref().next));
18 slow = slow.and_then(|v| v.as_ref().next);
19 }
20
21 if fast.is_none() || fast == slow {
22 break;
23 }
24 }
25
26 fast.is_some() && fast == slow
27}
28
29#[test]
30fn t_has_cycle() {

Callers

nothing calls this directly

Calls 2

is_noneMethod · 0.80
is_someMethod · 0.80

Tested by

no test coverage detected