Skip to content

Commit 5d3bf6a

Browse files
committed
linked-list-cycle
1 parent d9dd2d8 commit 5d3bf6a

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

linked-list-cycle/DaleSeo.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Definition for singly-linked list.
2+
#[derive(PartialEq, Eq, Clone, Debug)]
3+
pub struct ListNode {
4+
pub val: i32,
5+
pub next: Option<Box<ListNode>>,
6+
}
7+
8+
// TC: O(n)
9+
// SC: O(1)
10+
impl Solution {
11+
pub fn has_cycle(head: Option<Box<ListNode>>) -> bool {
12+
let mut slow = &head;
13+
let mut fast = &head;
14+
15+
while fast.is_some() && fast.as_ref().unwrap().next.is_some() {
16+
slow = &slow.as_ref().unwrap().next;
17+
fast = &fast.as_ref().unwrap().next.as_ref().unwrap().next;
18+
19+
if slow.as_ref().map(|node| node.as_ref() as *const _)
20+
== fast.as_ref().map(|node| node.as_ref() as *const _)
21+
{
22+
return true;
23+
}
24+
}
25+
26+
false
27+
}
28+
}

0 commit comments

Comments
 (0)