-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0234_palindrome_linked_list.rs
More file actions
58 lines (50 loc) · 1.23 KB
/
Copy paths0234_palindrome_linked_list.rs
File metadata and controls
58 lines (50 loc) · 1.23 KB
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
51
52
53
54
55
56
57
58
#![allow(unused)]
pub struct Solution {}
use crate::util::linked_list::{to_list, ListNode};
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
impl Solution {
#[inline]
pub fn is_palindrome(mut head: Option<Box<ListNode>>) -> bool {
if head.is_none() {
return true;
}
let mut rev: Option<Box<ListNode>> = None;
let mut _nxt: Option<Box<ListNode>> = None;
// half to half
while head.is_some() {
if rev == head || rev == head.as_ref().unwrap().next {
return true;
}
_nxt = head.as_mut().unwrap().next.take();
head.as_mut().unwrap().next = rev;
rev = head;
head = _nxt;
}
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_234() {
assert_eq!(Solution::is_palindrome(to_list(vec![1, 2, 4])), false);
assert_eq!(Solution::is_palindrome(to_list(vec![1, 2, 2, 1])), true);
}
}