-
Notifications
You must be signed in to change notification settings - Fork 10
/
reverse_linked_list.rs
56 lines (54 loc) · 1.28 KB
/
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
use super::ListNode;
#[allow(clippy::missing_const_for_fn)]
fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut has_rev = None;
let mut not_rev = head;
while let Some(mut not_rev_node) = not_rev {
/*
H: has_rev
N: not_rev
M: mut not_rev_node
Before:
None 1->2->3
^ ^
H N/M
After:
None 1->2->3
^ ^ ^
H M N
*/
not_rev = not_rev_node.next;
/*
Before:
None 1->2->3
^ ^ ^
H M N
After:
None<-1 2->3
^ ^ ^
H M N
*/
not_rev_node.next = has_rev;
/*
Before:
None<-1 2->3
^ ^ ^
H M N
After:
None<-1 2->3
^ ^
H N
*/
has_rev = Some(not_rev_node);
}
has_rev
}
#[test]
fn test_traverse_two_list_node() {
use crate::linked_list::{arr_to_linked_list, linked_list_to_vec};
const TEST_CASES: [(&[i32], &[i32]); 1] = [(&[1, 2, 3], &[3, 2, 1])];
for (input, output) in TEST_CASES {
let head = arr_to_linked_list(input);
assert_eq!(linked_list_to_vec(&reverse_list(head)), output.to_vec());
}
}