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
| // @Title: 反转链表 (反转链表 LCOF)
// @Author: 15816537946@163.com
// @Date: 2022-02-02 14:07:28
// @Runtime: 0 ms
// @Memory: 2.4 MB
// 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(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
if head.is_none() {
return None;
}
let mut prev = None;
let mut cur = head;
while let Some(mut v) = cur.take() {
let next = v.next.take();
v.next = prev.take();
prev = Some(v);
cur = next;
}
prev
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_case1() {
let input = to_list(vec![1, 2, 3, 4, 5]);
assert_eq!(
Solution::reverse_list(input),
(to_list(vec![5, 4, 3, 2, 1])),
);
}
}
|