题解 | #删除链表的节点#

删除链表的节点

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

/**
 *  #[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类 
        * @param val int整型 
        * @return ListNode类
    */
    pub fn deleteNode(&self, head: Option<Box<ListNode>>, val: i32) -> Option<Box<ListNode>> {
        let mut head_v = Box::new(ListNode::new(-1));
        head_v.next = head;
        let mut p = &mut head_v;
        //为啥要take()
        //如果直接写会报错,提示如下。我想大概是因为,p本身是mut的,不能将mut p中的一部分ownership 直接move 走。要用take()函数会更安全
        //while let Some(nt) = p.next {
        /*
        cannot move out of `p.next` as enum variant `Some` which is behind a mutable referencerustcClick for full compiler diagnostic
        main.rs(31, 24): data moved here
        main.rs(31, 24): move occurs because `nt` has type `Box<ListNode>`, which does not implement the `Copy` trait
        main.rs(31, 30): consider borrowing here: `&`
         */
        while let Some(nt) = p.next.take() {
            if nt.val == val {
                p.next = nt.next;
            } else {
                p.next = Some(nt);
                // p = &mut p.next.as_mut().unwrap();
                p = p.next.as_mut().unwrap();
            }
        }

        head_v.next
        }
}

#rust#
全部评论

相关推荐

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