-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpalindrome_linked_list_234.rs
38 lines (31 loc) · 1.02 KB
/
palindrome_linked_list_234.rs
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
use crate::Solution;
impl Solution {
pub fn is_palindrome(head: Option<Box<ListNode>>) -> bool {
let mut slow = &head;
let mut fast = &head;
// Find the middle of the list
while fast.is_some() && fast.as_ref().unwrap().next.is_some() {
slow = &slow.as_ref().unwrap().next;
fast = &fast.as_ref().unwrap().next.as_ref().unwrap().next;
}
// Reverse the second half
let mut prev = None;
let mut current = slow.clone();
while let Some(mut node) = current {
current = node.next.take();
node.next = prev;
prev = Some(node);
}
// Compare both halves
let mut left = &head;
let mut right = &prev;
while right.is_some() {
if left.as_ref().unwrap().val != right.as_ref().unwrap().val {
return false;
}
left = &left.as_ref().unwrap().next;
right = &right.as_ref().unwrap().next;
}
true
}
}