leetcode/
reverse_print.rs

1//! # 剑指 Offer 06. 从尾到头打印链表
2//!
3//! 难度 简单
4//!
5//! 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
6//!
7//! ## 示例 1:
8//!
9//! ```text
10//! 输入:head = [1,3,2]
11//! 输出:[2,3,1]
12//! ```
13//!
14//! ## 限制:
15//!
16//! `0 <= 链表长度 <= 10000`
17//!
18//! See [leetcode](https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/)
19
20use crate::ListNode;
21
22pub struct Solution;
23
24impl Solution {
25    pub fn reverse_print(head: Option<Box<ListNode>>) -> Vec<i32> {
26        head.map(|mut head| {
27            if head.next.is_some() {
28                let mut v = Solution::reverse_print(head.next.take());
29                v.push(head.val);
30                v
31            } else {
32                vec![head.val]
33            }
34        }).unwrap_or(vec![])
35    }
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41    use crate::list;
42
43    #[test]
44    fn test() {
45        let cases = vec![
46            (vec![2,3,1], list![1,3,2]),
47            (vec![], list![]),
48        ];
49        for (expect, input) in cases {
50            assert_eq!(expect, Solution::reverse_print(input));
51        }
52    }
53}