题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
// #![feature(linked_list_cursors)]
use std::io::{self, *};
// use std::collections::LinkedList;
// type Link = Option<Box<Node<T>>>;
#[derive(Clone, Debug)]
struct Node<T> {
v: T,
next: Option<Box<Node<T>>>
}
struct List<T> {
head: Option<Box<Node<T>>>
}
impl<T: std::cmp::PartialEq> List<T> {
fn remove(&mut self, elem: T) {
if self.head.is_some() && self.head.as_ref().unwrap().v == elem {
self.head = self.head.as_mut().unwrap().next.take();
return
}
let mut this = &mut self.head;
while let Some(x) = &mut this.as_mut().unwrap().next {
if x.as_ref().v == elem {
this.as_mut().unwrap().next = x.next.take();
}
this = &mut this.as_mut().unwrap().next;
}
}
}
impl<T: std::cmp::PartialEq> Node<T> {
fn new(elem: T) -> Self {
Node {
v: elem,
next: None,
}
}
fn set_next(&mut self, node: Self) {
self.next = Some(Box::new(node));
}
fn find<'a>(&'a mut self, anchorv: T) -> Option<&'a mut Self> {
if self.v == anchorv {
return Some(self);
}
if let Some(ref mut x) = self.next {
return x.find(anchorv);
}
None
}
fn insert_after<'a>(&'a mut self, elem: T, anchorv: T) -> bool {
if let Some(x) = self.find(anchorv) {
let node = Node {
v: elem,
next: x.next.take(),
};
x.set_next(node);
true
} else {
false
}
}
}
fn main() {
let stdin = io::stdin();
let mut line = String::new();
stdin.read_line(&mut line);
let mut ns = line.trim().split(" ");
let n = ns.next().unwrap().parse::<u16>().unwrap();
// let mut l = LinkedList::new();
// l.push_back(ns.next().unwrap().parse::<u16>().unwrap());
// for i in 1..n {
// let nextv = ns.next().unwrap().parse::<u16>().unwrap();
// let anchorv = ns.next().unwrap().parse::<u16>().unwrap();
// let mut cursor = l.cursor_front_mut();
// while *cursor.current().unwrap() != anchorv {
// cursor.move_next();
// }
// if let Some(c) = cursor.current() {
// cursor.insert_after(nextv);
// }
// }
// let delectv = ns.next().unwrap().parse::<u16>().unwrap();
// let mut cursor = l.cursor_front_mut();
// while *cursor.current().unwrap() != delectv {
// cursor.move_next();
// }
// if let Some(c) = cursor.current() {
// cursor.remove_current();
// }
// for i in l.iter() {
// print!("{} ", i)
// }
let mut l = List {head: Some(Box::new( Node::new(ns.next().unwrap().parse::<u16>().unwrap())) )};
for i in 1..n {
l.head.as_mut().unwrap().insert_after(ns.next().unwrap().parse::<u16>().unwrap(), ns.next().unwrap().parse::<u16>().unwrap());
}
l.remove(ns.next().unwrap().parse::<u16>().unwrap());
let mut this = l.head;
while let Some(node) = this {
print!("{} ", node.v);
this = node.next;
}
}
深信服公司福利 839人发布