题解 | #从尾到头打印链表#rust

从尾到头打印链表

https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035

/**
 *  #[derive(PartialEq, Eq, Debug, Clone)]
 *  pub struct ListNode {
 *      pub val: i32,
 *      pub next: Option<Box<ListNode>>
 *  }
 * 
 *  impl ListNode {
 *      #[inline]
 *      fn new(val: i32) -> Self {
 *          ListNode {
 *              val: val,
 *              next: None,
 *          }
 *      }
 *  }
 */

struct Solution{

}

impl Solution {
    fn new() -> Self {
        Solution{}
    }

    /**
    * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
    * 
        * @param head ListNode类 
        * @return int整型一维数组
    */
    pub fn printListFromTailToHead(&self, head: Option<Box<ListNode>>) -> Vec<i32> {
        // write code here
        let mut result = Vec::new();
        let mut current = head;
	  	//要用while let解构赋值
        while let Some(node) = current {
            result.push(node.val);
            current = node.next;
        }

        result.reverse();
        result
    }
}

option 相关知识点

https://course.rs/basic/match-pattern/option.html

while let相关知识点

https://course.rs/basic/match-pattern/pattern-match.html#while-let-%E6%9D%A1%E4%BB%B6%E5%BE%AA%E7%8E%AF

#rust#
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务