-
Notifications
You must be signed in to change notification settings - Fork 0
/
palindrome-linked-list.rs
60 lines (55 loc) · 1.41 KB
/
palindrome-linked-list.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
struct Solution;
// 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 {
pub fn is_palindrome(head: Option<Box<ListNode>>) -> bool {
let mut head = head;
let mut v: Vec<i32> = Vec::new();
while let Some(node) = head {
v.push(node.val);
head = node.next;
}
for i in 0..v.len() / 2 {
if v[i] != v[v.len() - i - 1] {
return false;
}
}
true
}
}
fn main() {
println!("{}", Solution::is_palindrome(None));
}
#[cfg(test)]
mod tests {
use crate::{ListNode, Solution};
#[test]
fn test_impl1() {
let node = Some(Box::new(ListNode {
val: 1,
next: Some(Box::new(ListNode {
val: 2,
next: Some(Box::new(ListNode {
val: 2,
next: Some(Box::new(ListNode { val: 1, next: None })),
})),
})),
}));
assert!(Solution::is_palindrome(node));
let node = Some(Box::new(ListNode {
val: 1,
next: Some(Box::new(ListNode { val: 2, next: None })),
}));
assert!(!Solution::is_palindrome(node));
}
}