-
Notifications
You must be signed in to change notification settings - Fork 0
/
s0206_reverse_linked_list.rs
84 lines (78 loc) · 2.31 KB
/
s0206_reverse_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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
struct Solution;
use rustgym_util::*;
//leetcode submit region begin(Prohibit modification and deletion)
// 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 reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
head.as_ref()?;
let mut prev = head.unwrap();
let mut curr = prev.next.take();
while let Some(mut node) = curr {
curr = node.next.replace(prev);
prev = node;
}
Some(prev)
}
pub fn reverse_list_recursive(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
fn rev(curr: Option<Box<ListNode>>, prev: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
if let Some(mut node) = curr {
let next = node.next;
node.next = prev;
rev(next, Some(node))
} else {
prev
}
}
rev(head, None)
}
}
//leetcode submit region end(Prohibit modification and deletion)
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
let head = list!();
let res = list!();
assert_eq!(Solution::reverse_list(head), res);
let head = list!(1);
let res = list!(1);
assert_eq!(Solution::reverse_list(head), res);
let head = list!(1, 2);
let res = list!(2, 1);
assert_eq!(Solution::reverse_list(head), res);
let head = list!(1, 2, 3);
let res = list!(3, 2, 1);
assert_eq!(Solution::reverse_list(head), res);
}
#[test]
fn test_recursive() {
let head = list!();
let res = list!();
assert_eq!(Solution::reverse_list_recursive(head), res);
let head = list!(1);
let res = list!(1);
assert_eq!(Solution::reverse_list_recursive(head), res);
let head = list!(1, 2);
let res = list!(2, 1);
assert_eq!(Solution::reverse_list_recursive(head), res);
let head = list!(1, 2, 3);
let res = list!(3, 2, 1);
assert_eq!(Solution::reverse_list_recursive(head), res);
}
}