题解 | #删除链表的节点# | Rust
删除链表的节点
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 ans = Box::new(ListNode::new(-1)); ans.next = head; let mut cur = &mut ans; while cur.next.is_some() { if cur.next.as_ref().unwrap().val == val { cur.next = cur.next.as_mut().unwrap().next.take(); } else { cur = cur.next.as_mut().unwrap(); } } return ans.next; } }