题解 | #删除链表中重复的结点#
删除链表中重复的结点
https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef
- rust中尽量使用少点变量,因为涉及到很多所有权问题,转来转去很麻烦
- 整体思路,先添加一个头节点
- 遍历一次链表,找出出现过两次及以上的,加入hashset中
- 遍历一次链表,如果该节点的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#