题解 | #删除链表中重复的结点#

删除链表中重复的结点

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

  1. rust中尽量使用少点变量,因为涉及到很多所有权问题,转来转去很麻烦
  2. 整体思路,先添加一个头节点
  3. 遍历一次链表,找出出现过两次及以上的,加入hashset中
  4. 遍历一次链表,如果该节点的val存在hashset中就删除

/**
 *  #[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,
 *          }
 *      }
 *  }
 */


use std::collections::HashSet;
struct Solution;

impl Solution {
    // 实现 Solution 的构造函数
    fn new() -> Self {
        Solution{}
    }

    /**
    * 删除链表中重复的节点
    * 
    * @param pHead 输入的 ListNode 链表
    * @return 删除重复节点后的 ListNode 链表
    */
    pub fn deleteDuplication(&self, pHead: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
        //构造一个头节点
        let head = pHead;
        let mut dummy_head = Some(Box::new(ListNode::new(-1)));
        dummy_head.as_mut().unwrap().next = head;

        //找出需要删除的val
        let mut hs = HashSet::new();
        let mut pre = &mut dummy_head;
        // let cur = &mut pre.as_mut().unwrap().next;

        while pre.as_mut().unwrap().next.is_some() {
            let pre_val = pre.as_mut().unwrap().val;
            let cur_val = pre.as_mut().unwrap().next.as_mut().unwrap().val;
            if pre_val == cur_val {
                hs.insert(pre_val);
            }
            //pre往下走,cur往下走
            pre = &mut pre.as_mut().unwrap().next;
        }

        let mut pre = &mut dummy_head;

        while pre.as_mut().unwrap().next.is_some() {
            let cur_val = pre.as_mut().unwrap().next.as_mut().unwrap().val;
            if hs.contains(&cur_val) {
                pre.as_mut().unwrap().next =
                    pre.as_mut().unwrap().next.as_mut().unwrap().next.take();
            } else {
                //为啥上面那行需要用take() 不需要&mut  --- 为啥上面不需要&mut ,因为next不是&mut 类型option即可
                //为啥下面这行需要&mut 而不需要take() ---- 需要&mut 因为本来pre 就是&mut类型 
                //
                pre =&mut pre.as_mut().unwrap().next;
            }
        }

        dummy_head.unwrap().next
    }
}

#rust#
全部评论

相关推荐

zzzzhz:兄弟你先猛猛投简历至少三百家,能约到面试就去面。最近可以速成智能小车,智慧家居烂大街的项目,不需要自己写,只需要把里面的代码讲解看明白就行。把其中涉及到的八股文都拿出来单独背一下,我去年找工作就一个智能小车智慧家居找了10k差不多。
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-11 17:10
什么素质,我请问呢,要掉小珍珠了。。。又憋屈又生气
苍蓝星上艾露:给它们能的,一群dinner牛马挥刀向更弱者罢了。我写的开源求职AI co-pilot工具,优化你的简历,找到你匹配的岗位,定制你的简历,并让你做好面试准备https://github.com/weicanie/prisma-ai
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务